Reading data from files
I have a text file with the following lines:
1 | Matrix | 1 | Action | 3
2 | X-men 2 | 1 | Action | 2
id | movie name | rental type | genre | stock
I want to read the data from the text file and store 1 into an id variable, Matrix into a movie string etc etc.
Any ideas on how to accomplish this?
I have thought of a few ways to implement this such as by using fgetc and manually checking every char for a '|' but what I would like to do is to use fscanf which would make the whole process much easier. Unfortunately fscanf would not be able to read X-men 2 as a single string.
Thanks in advance.
Assuming that your string buffers are 101 characters in length:
fscanf("%d | %100[^|] | %d | %100[^|] | %d", &id, nameBuf, &type, genreBuf, &stock);
I would probably use fgets and strchr.
Edit: yeah it works... thanks alot man. Going to look up what the %[ specifier does exactly now. Mind explaining how it works in detail?
>Mind explaining how it works in detail?
Any book on C can tell you, but you can think of it as a simple regular expression. A character is read from the stream as long as it is inside the character set (inside the square brackets). The ^ symbol compliments the entire set so that it matches anything not in the set. So %100[^|] will read at most 100 characters or until a | is found.