Square Square - 11 days ago 4
C Question

How can I know text file is empty or not?(in C)

I'm trying to detect text file is empty or not in C.
(values are initialized in NULL)
Whenever read first in value(using fscanf), it always returns file has zero,
even if it has value "0" or "empty".

How can I know the target text file is empty or not?
(it should be distinguished even it has "0" in first letter)

Answer

If the file was successfully open for read, as per fopen(filename, "r"), you can verify if it is empty before any read operation this way:

int is_empty_file(FILE *fp) {
    int c = getc(fp);
    if (c == EOF)
        return 1;
    ungetc(c, fp);
    return 0;
}

ungetc() is guaranteed to work for at least one character. The above function will return 1 if the file is empty or if it cannot be read, due to an I/O error. You can tell which by testing ferr(fp) or feof(fp).

If the file is a stream associated to a device or a terminal, the test code will block until at least one byte can be read, or end of file is signaled.

If the file is a regular file, you could also use a system specific API to determine the file size, such as stat, lstat, fstat (on Posix systems).

Comments