简体   繁体   中英

C Syntax related to fgetc() and ungetc()

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?

You might want to call fgetc outside of the loop conditional:

int c = fgetc(stream);
while(c != EOF){
    ....
    c = fgetc(stream);
}

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 ).


EDIT (bonus): As for you pseudocode of skip 30 bytes , you may want to take a look at the fseek function manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM