Reputation: 9
In my code I am trying to accomplish something like this (written in pseudocode):
While not at EOF:
Get line
Write line to different file
Skip 30 bytes
Currently, the best way I can think of to do this is something like this:
int c;
while((c = fgetc(stream)) != EOF){
ungetc(c,stream);
REST OF CODE
Is there a better way to check if I am at the EOF but still use the character that I am currently reading?
Upvotes: 0
Views: 1019
Reputation: 3094
You can use fgetc
like this:
while ((c = fgetc(fp)) != EOF) {
...
}
OR, since you want to read lines (as your pseudocode says), you can use fgets:
char *fgets(char *s, int size, FILE *stream);
And you would use it as:
char *buffer = malloc(500);
while (fgets(buffer,500, fp)) {
// treat line here
}
From the manual:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
And the return:
fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.
This means the return of the fgets
function can be used as the condition for the while
loop (so you don't need to do the != EOF
).
skip 30 bytes
, you may want to take a look at the fseek function manual.
Upvotes: 1
Reputation: 223897
You might want to call fgetc
outside of the loop conditional:
int c = fgetc(stream);
while(c != EOF){
....
c = fgetc(stream);
}
Upvotes: 1