【问题标题】:How to read beyond new line characters using fgets() function?如何使用 fgets() 函数读取换行符以外的字符?
【发布时间】:2018-12-31 12:32:43
【问题描述】:

我从 C 手册页了解到,使用 fgets(),在 EOF 或换行符后停止读取。我有一个程序从文件中读取(多行)并在新行的末尾停止读取。

有没有办法强制fgets() 忽略换行符并读到EOF

while(fgets(str,1000, file))
{ 
 // i do stuffs with str here
}

【问题讨论】:

  • 您会考虑使用其他功能吗?因为就fgets() 而言,它会停止一次,它要么得到一个换行符,要么得到一个文件结尾。
  • @P.W: getline 的行为类似于 fgets,希望它为您管理内存。它不会解决换行问题。 (但 getdelim 带有空分隔符可能会起作用。不过,两者都是非标准函数。)
  • fgets 不是从文件中读取数据的唯一函数。如果您想将整个文件保存在内存中,只需read 即可。 (最好确保分配了足够的内存。)
  • @MOehm:这是我与 C++ getline 的混淆,可以指定分隔符。

标签: c fgets


【解决方案1】:

有没有办法强制fgets() 忽略换行并阅读到EOF

不,您不能,因为fgets() 的实现方式是,如果发生 end-of-file换行符,解析将停止成立。可以考虑使用其他文件输入/输出功能,如fread()

【讨论】:

    【解决方案2】:

    在 while 循环中,您必须进行以下检查:

    while ((fgets(line, sizeof (line), file)) != NULL)
    

    成功时,函数返回相同的 str 参数。如果遇到 End-of-File 并且没有读取任何字符,则 str 的内容保持不变并返回一个空指针。 如果发生错误,则返回一个空指针。

    代码示例:

    #include <stdio.h>
    int main()
    {
        char *filename = "test.txt";
        char line[255];
        FILE *file;
        file = fopen(filename, "r");
        while ((fgets(line, sizeof (line), file)) != NULL) {
            printf("%s", line);
        }
        fclose(file);
        return 0;
    }
    

    【讨论】:

    • 谢谢,fgets() 返回NULL on` \n` 或EOF 所以即使在fgets() 以上的sn-p 上也会在找到的第一个新行处停止。 @samuil
    • cplusplus.com/reference/cstdio/fgets 来自参考 fgets() 仅当到达文件末尾或发生其他错误时才会返回 NULL。如果它设法读取该行,它将不会返回 NULL。也许您读取的文件有问题:) 不知道
    【解决方案3】:

    不,fgets 在遇到 \n(换行符)字符后停止读取。

    否则,您必须自己查找并删除换行符。

    Or you can usefread:

    C 库函数 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) 将给定流中的数据读入数组 由 ptr 指向。

    成功读取的元素总数返回为 size_t 对象,它是一个整数数据类型。如果这个数字不同 从 nmemb 参数,然后发生错误或 End 文件已到达。

    /* fread example: read an entire file */
    #include <stdio.h>
    #include <stdlib.h>
    
    int main () {
      FILE * pFile;
      long lSize;
      char * buffer;
      size_t result;
    
      pFile = fopen ( "myfile.bin" , "rb" );
      if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
    
      // obtain file size:
      fseek (pFile , 0 , SEEK_END);
      lSize = ftell (pFile);
      rewind (pFile);
    
      // allocate memory to contain the whole file:
      buffer = (char*) malloc (sizeof(char)*lSize);
      if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
    
      // copy the file into the buffer:
      result = fread (buffer,1,lSize,pFile);
      if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
    
      /* the whole file is now loaded in the memory buffer. */
    
      // terminate
      fclose (pFile);
      free (buffer);
      return 0;
    }
    

    【讨论】:

    • 古玩:为什么 sizeof(char) *malloc (sizeof(char)*lSize) 中?而不是 buffer = malloc (lSize);?
    猜你喜欢
    • 2020-02-17
    • 2018-05-28
    • 2017-02-11
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多