c - fgets 不移动文件指针

标签 c fgets file-pointer

我有一个可能相当简单的问题。我有一个文件 input.txt 是:

cat input.txt

testsuite1
test1
summary information of test
FAIL
testsuite2
test1
summary info ya
PASS

我正在编写一个程序,只是将这些字符串中的每一个读入变量并进行进一步处理。最好的方法是什么?我目前正在做:

main() {
    FILE *fp;
    char testsuite[100],testname[100],summary[100],result[100];
    fp = fopen("input.txt", "r");
    while(1) {
        if(fgets(testsuite,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        if(fgets(testname,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        if(fgets(summary,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        if(fgets(result,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        printf("testsuite: %s testname:%s summary:%s result:%s \n",testsuite,testname,summary,result);
    }


    fclose(fp);
}

有更好的方法吗?我目前面临的问题是,如果 input.txt 包含哪怕一个空白行,空白 like 被读入一个变量。避免它的最佳方法是什么?

谢谢!

最佳答案

您应该编写自己的函数来跳过空行(例如称为 getline())并使用它代替 fgets():

char *getline(char *buf, int size, FILE *fp)
{
    char *result;
    do {
        result = fgets(buf, size, fp);
    } while( result != NULL && buf[0] == '\n' );
    return result;
}

您现在可以优化该函数以跳过仅包含空格或任何您需要的行。

关于c - fgets 不移动文件指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24165828/

相关文章:

c - fgets 在退出 EOF 之前循环多次

c++ - 如何使用 FILE *fp 调用函数关闭文件

c - 将命令行参数从主函数传递给用户定义的 C 函数

c - 您将如何从其他 C/C++ 文件访问静态变量?

c - Mario.c 编码问题

c - 变量的双重定义

c++ - c中的升序和降序

c - 用 C 程序读取文本文件导致处理器以 100% 运行

php - 逐行读取文件的更快方法?

c - parent 是否在 child 退出时看到管道eof?