mac怎么实现文件读写c语言,使用Sublime Text和Xcode在Mac上进行文件输入/输出。 C语言...
f1name和f2name应的字符来存储文件名的数组。你已经将它们定义为字符,并试图在其中存储字符串将调用未定义的行为,因为scanf将执行非法内存访问。
另外,main函数的签名应该是以下任一项。
int main(void);
int main(int argc, char *argv[]);
你应该修改你的程序
#include
#include
int main(void) {
// variable name SSN change to lowercase
int ssn, n, i;
int retval; // to save the return value of fscanf
float wages, total;
char f1name[30+1], f2name[30+1];
// define file pointers inside main
// also change the name to lowercase
FILE *f1, *f2;
scanf("%30s", f1name);
f1 = fopen(f1name, "r");
// check for error in opening file
if(f1 == NULL) {
// print error message to stderr
perror("error in opening file\n");
// handle it
}
retval = fscanf(f1, "%d", &n);
if(retval != 1) {
perror("error in reading from the file\n");
// handle it
}
for(i = 0; i < n; i++) {
retval = fscanf(f1,"%d%f", &ssn, &wages);
if(retval != 2) {
perror("error in reading from the file\n");
// handle it
}
total += wages;
}
scanf("%30s", f2name);
f2 = fopen(f2name, "w");
// check for error in opening file
if(f2 == NULL) {
// print error message to stderr
perror("error in opening file\n");
// handle it
}
// Writing to the file the average of all earnings
fprintf(f2,"%d %f", ssn, total/n);
// Closing the file
fclose(f1);
fclose(f2);
return 0;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
