简体   繁体   中英

How to iterate through a file twice by using while((c = getc(file)) != EOF)?

#include <stdio.h>

int main(int argc, char **argv) {
    int c;
    FILE *file;
    file = fopen(argv[1], "r");
    if (file) {

        while ((c = getc(file)) != EOF) {
            if (c == 'a') {
                // loops through this part of the file without breaking the 
                // the original c
            }
        }


    }
}

Basically, this program has really no purpose just wondering if there is a easy way to loop twice in a file.

like for example say the contents of a file is "1234a456468"

when c is at index 4. I want to make another loop without affecting c, we'll call another variable d, where d is at index 4 as well and I can use d = getc(file) without it affecting c.

Use fseek and ftell :

#include <stdio.h>

int main(int argc, char **argv) {
    int c;
    FILE *file;
    long remember_pos;
    file = fopen(argv[1], "r");
    if (file) {

        while ((c = getc(file)) != EOF) {
            remember_pos = ftell(file);
            if (c == 'a') {
                // loops through this part of the file without breaking the 
                // the original c
            };
            fseek(file, remember_pos, SEEK_SET);
        }
    }
}

man page: https://www.freebsd.org/cgi/man.cgi?query=fseek

take a look at the command fseek reference

it jumps to an offset from Start/End/Current-position of File

to jump to start use fseek(f, 0, SEEK_SET) which is equivalent to rewind(f)

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