简体   繁体   中英

How do i check if a file is empty in C?

I'm importing a txtfile into my file, how do i check if the input file is blank.

I already check if it cannot read the input. This is what i have so far:

#include<stdio.h>
#include<stdlib.h>

int main (int argc, char *argv[]){

// argv[1] will contain the file name input. 

FILE *file = fopen(argv[1], "r");

// need to make sure the file is not empty, error case. 

if (file == NULL){
    printf("error");
    exit(0);
}
 // if the file is empty, print an empty line.

int size = ftell(file); // see if file is empty (size 0)
if (size == 0){
    printf("\n");
}
printf("%d",size);

the size checking obviously does not work because i put in a few numbers and the size is still 0. any suggestions?

You can use sys/stat.h and call the value of the st_size struct member:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main (int argc, char *argv[]) {
    if (argc != 2) {
        return EXIT_FAILURE;
    }
    const char *filename = argv[1];
    struct stat st;
    if (stat(filename, &st) != 0) {
        return EXIT_FAILURE;
    }
    fprintf(stdout, "file size: %zd\n", st.st_size);
    return EXIT_SUCCESS;
}

how about try read first row. and see what characters you get?

Call ftell() does not tell you the size of the file. From the man page:

The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream.

That is, it tell you your current position in the file...which will always be 0 for a newly opened file. You need to seek to the end of the file first (see fseek() ).

ftell will tell you the position the file pointer is at, and immediately after you opened the file, this position is always 0.

You either use stat before opening, or use fseek to seek some distance in the file (or at end) and then use ftell .

Or you delay the check until afterwards. Ie, you try to read whatever you need to read, and then verify whether you succeeded or not.

Update : and speaking of checks, you have no guarantee that

// argv[1] will contain the file name input. 

For that, you need to check out that argc is at least 2 (the first argument being the executable name). Otherwise your file name might be NULL . fopen should simply return NULL , but in other scenarios you might find yourself looking at a core dump.

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