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

2020-06-23 04:58发布

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.

8条回答
Emotional °昔
2楼-- · 2020-06-23 05:35

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楼-- · 2020-06-23 05:37

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楼-- · 2020-06-23 05:41
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

查看更多
淡お忘
5楼-- · 2020-06-23 05:46

you can use the feof() function. example:

if(feof(file))
{
    printf("empty file\n");
}
查看更多
甜甜的少女心
6楼-- · 2020-06-23 05:54

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
     }
查看更多
Emotional °昔
7楼-- · 2020-06-23 05:54

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

查看更多
登录 后发表回答