【问题标题】:Reading a text file up to a certain character读取文本文件到某个字符
【发布时间】:2011-03-20 00:00:40
【问题描述】:

这是我的困境。我有一个文件,并希望读取所有字符,直到程序点击“#”,并忽略“#”之后该行的所有内容。例如

0 4001232 0 #评论,丢弃

这令人沮丧,因为感觉有一个非常简单的解决方案。谢谢!

【问题讨论】:

  • 我有一种感觉,您希望有人为您提供所有代码。

标签: c parsing


【解决方案1】:
FILE *f = fopen("file.txt", "r");
int c;
while ((c = getc(f)) != '#' && c != EOF)
   putchar(c);

【讨论】:

    【解决方案2】:

    使用fgets 读取一行,通读该行直到得到一个“#”字符。

    再读一行...

    【讨论】:

      【解决方案3】:

      有很多方法和例子来说明如何做到这一点。通常,这个想法是有一个变量来保存状态(在 # 之前,在 # 之后,在 \n 之后等)并在 while 循环中运行直到 EOF。一个例子你可以看到here它是一个去除C cmets的程序,但是思路是一样的。

      【讨论】:

        【解决方案4】:
        filePointer = fopen("person.txt", "r");
        
        do
        {
            read = fgetc(filePointer);
            //stop when '#' read or when file ends
            if (feof(filePointer) || read == '#')
            {
                break;
            }
            printf("%c", read);
        } while (1);
        
        fclose(filePointer);
        

        你最好检查一下文件是否打开成功

        if (filePointer == NULL)
        {
            printf("person.txt file failed to open.");
        }
        else
        {
            file operations
        }
        

        【讨论】:

          【解决方案5】:

          解决方案取决于您如何“阅读”它。

          例如,我可以在 bash 中删除所有带有 sed 's/#.*//' <infile >outfile 的 cmets。

          编辑:但是,如果我手动解析它,我可以简单地(在我的解析它的循环中)有

          if(line[i]=='#') {
              continue;
          }
          

          这将通过退出循环来停止解析该行。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-27
            • 2012-01-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多