0

想学C。想读一个文本文件的第一行,我的代码是:

#include <stdio.h>
int main()
{

    FILE *in = fopen("test.txt", "rt");
    // read the first line from the file
    char buffer[100];
    fgets(buffer, 20, in);
    printf("first line of \"test.txt\": %s\n", buffer);
    fclose(in);
    return 0;
}

我在 xCode 中这样做。我收到一个非常糟糕的访问错误。test.txt 肯定存在。它有一行写着“这是一个文本文件”

4

3 回答 3

1

打电话后试试这个fopen()

if(in == NULL){
    printf("Can't read teste.txt because: %s.\n", strerror(errno));
    return 1;
 }

并添加标题:

#include <errno.h>
#include <string.h>
于 2012-04-16T20:11:21.637 回答
0

您不检查是否FILE为NULL。由于多种原因,它可能无法打开。

于 2012-04-16T20:01:23.647 回答
0

代码看起来不错,所以我的猜测是程序没有在与文件相同的工作目录中运行。尝试将文件放入,例如,/tmp/test.txt并在fopen.

于 2012-04-16T20:02:52.333 回答