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;
}
總結
以上是生活随笔為你收集整理的mac怎么实现文件读写c语言,使用Sublime Text和Xcode在Mac上进行文件输入/输出。 C语言...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言 号咋打,C语言C语言中的开头#号
- 下一篇: c语言 双线程,如何用C语言实现多线程