读取特定字符的文本文件

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

0 4001232 0 #comment,丢弃

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

FILE *f = fopen("file.txt", "r"); int c; while ((c = getc(f)) != '#' && c != EOF) putchar(c); 

有很多方法和例子可以做到这一点。 通常,想法是拥有一个保持状态的变量(在#之前,在#之后,在\ n之后等)并且在while循环中运行直到EOF。 你可以在这里看到一个例子,它是一个删除C注释的程序,但这个想法是一样的。

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

例如,我可以在bash中使用sed 's/#.*//' outfile删除所有这些注释。

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

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

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

使用fgets读取一行,读取这一行,直到你得到一个’#’字符。

读另一行……

在我看来,这比预解决问题要多一些。 无论如何,有许多工具和命令专门做你所要求的。 如果可能,最好使用它们。

但是,如果您需要或想要在代码中执行此操作,那么,正如已经提到的那样,您可以根据状态保持当前状态并处理任何新字符。 这是一种非常好的通用方法,强烈建议使用,特别是需要进行更多的预处理。

但是,如果这绝对是你唯一要做的事情,那么你可以做一些更好的事情,并用这样的代码放弃状态:

 do { // Initialize things (buffer for the characters maybe) per line ch = fgetc(input_file); while ( (ch != EOF) && (ch != '\n') && (ch != '#') ) // Assuming # is the comment character { // Do something with 'ch', save it to a buffer, give it to a function - whatever ch = fgetc(input_file); } // If you save the characters to a buffer, this will be a good time to do something with it while ( (ch != EOF) && (ch != '\n') ) ch = fgetc(input_file); // Read the rest of the line while ( ch != EOF );