循环遍历C中文件的每一行

err*_*ler 2 c file-io

我想知道如何循环遍历文件的每一行,这是我到目前为止的代码:

FILE *todoFile;
todoFile = fopen("./todo.txt", "r");

if (todoFile != NULL) {

} else {
    printf("ERROR");
}
Run Code Online (Sandbox Code Playgroud)

pmg*_*pmg 8

逐行读取文件的惯用方法是

    /* assume line is a char array */
    while (fgets(line, sizeof line, handle)) {
        size_t len = strlen(line);
        if (len && (line[len - 1] != '\n')) {
            /* incomplete line */
        }
        /* possibly remove trailing newline ... and */
        /* deal with line */
    }
Run Code Online (Sandbox Code Playgroud)

  • @errorhandler:将你的行限制设置为4096(不是很小,很容易超过256).POSIX [`<limits.h>`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html#tag_13_24)设置限制LINE_MAX,其最小允许值为_POSIX2_LINE_MAX ,这是值2048.您的机器有多少GiB的主内存?它不会注意到4 KiB! (2认同)