Home > Software engineering >  Reading a file until content end (EOF is reached)
Reading a file until content end (EOF is reached)

Time:03-24

(Despite the fact, reading 1 char at time is system expensive) Why the following function is not stopping after the content of a file ended? Currently I am running the function using command line inputs for the path of the file and cmd as teminal.

Here is the code:

int flen(int file){
    int i;
    char c = 0;
    for(i = 0; c != EOF; i  ){
        read(file, &c, 1);
    }
    return i;
}

int main(int argc, char *argv[]){
    long long len;
    int fd;
    if(argc != 2){
        fprintf(stderr, "Usage: %s <valid_path>\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    if((fd = open(argv[1], O_RDONLY, 0)) == -1){
        fprintf(stderr, "Fatal error wihile opening the file.\n");
        exit(EXIT_FAILURE);
    }

    len = flen(fd);
    printf("%d\n", len);

    exit(0);
}

I think the problem could be related with EOF in the for loop condition. But if this is true, how can I know when the file actually ends?

CodePudding user response:

You should test the return value from read instead.

Return Value: the number of bytes read
If the function tries to read at end of file, it returns 0.
If execution is allowed to continue, the function returns -1.

long long flen(int file) {
    long long i = 0;
    char c;
    while(read(file, &c, 1) == 1) {
        i  ;
    }
    return i;
}

Aside: you have a type mismatch with int flen() and long long len.

  • Related