Reading a text file to a specific character

Here is my dilemma. I have a file and you want to read all the characters until the program presses "#" and ignores everything on this line after "#". for instance

0 4001232 0 #comment, discard

This is frustrating as it seems that there is a very simple solution. Thanks!

+4
source share
5 answers
FILE *f = fopen("file.txt", "r"); int c; while ((c = getc(f)) != '#' && c != EOF) putchar(c); 
+2
source

There are many ways and examples of how to do this. Usually the idea is to have a variable that contains state (before #, after #, after \ n, etc.) and work in a while loop before EOF. for example, you can see here is a program to remove C comments, but the idea is the same.

+1
source

The decision depends on how you read it.

I could, for example, just delete all these comments with sed 's/#.*//' <infile >outfile in bash.

EDIT: However, if I parsed it manually, I could simply (in my loop to parse it) have

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

which will stop parsing this line, exiting the loop.

0
source

Read the line using fgets , read this line until you get the "#" character.

Read another line ...

0
source

This is a bit more preprocessing than a parsing issue. In any case, there are many tools and commands that specialize in doing just what you ask. If possible, it is best to use them.

If you need or want to do this inside your code, than the usual method for this, as already mentioned, save the current state in yours and process any new character in accordance with the state. This is a very good general method, and it is highly recommended, especially there is a lot of preprocessing that needs to be done.

If, however, this is absolutely the only thing you need to do, than you can do something a little better and abandon the state with this code:

 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 ); 
0
source

Source: https://habr.com/ru/post/1344412/


All Articles