How to check if a file has content or not using C?

2020-06-23 05:54发布

问题:

I have a source file file1 and a destination file file2, here I have to move content from file1 to file2.

So I have to do some validation first.

  1. I must check source file is existing or not? I can check using this:

    fp = fopen( argv[1],"r" );
    if ( fp == NULL )
    {
        printf( "Could not open source file\n" );
        exit(1);
    } 
    
  2. Then I have to check if the source file has any content or not? If it is empty, I have to throw some error message.

This is what I've tried until the moment.

回答1:

C version:

if (NULL != fp) {
    fseek (fp, 0, SEEK_END);
    size = ftell(fp);

    if (0 == size) {
        printf("file is empty\n");
    }
}

C++ version (stolen from here):

bool is_empty(std::ifstream& pFile)
{
    return pFile.peek() == std::ifstream::traits_type::eof();
}


回答2:

You can do this without opening the file as well using the stat method.

#include <sys/stat.h>
#include <errno.h>

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

     struct stat stat_record;
     if(stat(argv[1], &stat_record))
         printf("%s", strerror(errno));
     else if(stat_record.st_size <= 1)
         printf("File is empty\n");
     else {
         // File is present and has data so do stuff...
     }

So if the file doesn't exist you'll hit the first if and get a message like: "No such file or directory"

If the file exists and is empty you'll get the second message "File is empty"

This functionality exists on both Linux and Windows, but on Win it's _stat. I haven't tested the windows code yet, but you can see examples of it here.



回答3:

Just look if there's a character to read

int c = fgetc(fp);
if (c == EOF) {
    /* file empty, error handling */
} else {
    ungetc(c, fp);
}


回答4:

You can use fseek using SEEK_END and then ftell to get the size of a file in bytes.



回答5:

fseek(fp, 0, SEEK_END); // goto end of file
if (ftell(fp) == 0)
 {
      //file empty
 }
fseek(fp, 0, SEEK_SET); // goto begin of file
// etc;

reference for ftell and example

reference for fseek and example



回答6:

you can check if the file size > 0

after your code of checking file exist (before you close the file) you add the following code

   size = 0
    if(fp!=NULL)
    {
        fseek (fp, 0, SEEK_END);

        size = ftell (fp);
        rewind(fp);

    }
    if (size==0)
    {
      // print your error message here
     }


回答7:

It is painful to open the data and count each byte of the file. It is better to ask to the operating system to give you details about the files you want to used. The API relies depends on your operating system as Mike previously said.



回答8:

you can use the feof() function. example:

if(feof(file))
{
    printf("empty file\n");
}