【问题标题】:File Input/Output on a Mac using Sublime Text and Xcode. C language使用 Sublime Text 和 Xcode 在 Mac 上输入/输出文件。 C语言
【发布时间】:2014-05-19 04:10:51
【问题描述】:

所以我的第一个问题是,如何使用 Xcode 和终端在 Mac 上执行文件输入/输出程序?

其次,在我弄清楚之前,有人介意告诉我这是否正确,因为我目前无法编译和运行它吗?这周我打算对我的驱动器进行分区并在上面扔窗户,但在那之前我想为考试而学习。

这是练习题: 编写一个程序,从第一行读入一个整数 n,然后在随后的 n 行中,每行两件事(一个 int SSN 和一个浮动工资收入)。这一切都形成了一个文件。您必须将文件名提示为长度一定小于 30 个字符的字符串。打开文件等,读取所有内容,并保持所有工资的总和,然后当读取完成时,提示输出文件名字符串,打开它并将所有收入的平均值写入其中。

这是我的代码:

#include <stdlib.h>
#include <stdio.h>

FILE *F1, *F2;

void main () {

int SSN, n, i;
float wages, total;
char f1name, f2name;

scanf("%s", &f1name);
F1 = fopen("f1name", "r");

fscanf(F1,"%d", &n);
{

// Reading in the 
for(i=0; i<n; i++)
    {
    fscanf(F1,"%d%f", &SSN, &wages);
    total += wages;
    }

// Scanning in file name and opening it
scanf("%s", &f2name);
F2 = fopen(fname, "w");

// Writing to the file the average of all earnings
fprintf(F2,"%d%f", SSN, total/n);
}

// Closing the file
fclose(F1);
fclose(F2);

}

【问题讨论】:

标签: c macos io


【解决方案1】:

f1namef2name 应该是用于存储文件名的字符数组。您已将它们定义为字符,尝试在其中存储字符串会引发未定义的行为,因为 scanf 会进行非法内存访问。

另外,main 函数的签名应该是以下之一。

int main(void);
int main(int argc, char *argv[]);

你应该修改你的程序来

#include <stdio.h>
#include <stdlib.h>

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;
}

【讨论】:

  • +1,但如果错误消息报告在标准错误而不是标准输出上会更好。它还应该检查每个fscanf() 调用是否返回预期数量的值;如果没有,可能是时候报告错误并退出了。作为一般的经验法则,从标准输入读取文件名而不是将它们作为程序的参数是次优的,但我意识到这是给你工作的设计。
  • @JonathanLeffler 进行了您建议的更改。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
相关资源
最近更新 更多