我怎么知道文本文件是否为空?(在C中)

时间:2016-11-23 12:00:13

标签: c file-io

我试图在C中检测文本文件是否为空。 (值初始化为NULL) 每当读取第一个值(使用fscanf)时,它总是返回文件为零, 即使它有价值" 0"或"空"。

我如何知道目标文本文件是否为空? (即使它有" 0"在第一个字母中也应该被区分)

3 个答案:

答案 0 :(得分:1)

如果文件已成功打开以进行读取,则按照fopen(filename, "r"),您可以在执行任何读取操作之前验证它是否为空:

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

ungetc()保证适用于至少一个角色。如果文件为空或由于I / O错误而无法读取,则上述函数将返回1。您可以通过测试ferr(fp)feof(fp)确定哪个。

如果文件是与设备或终端关联的流,则测试代码将阻塞,直到可以读取至少一个字节或发出文件结束信号。

如果文件是常规文件,您还可以使用特定于系统的API来确定文件大小,例如statlstatfstat(在Posix系统上)。

答案 1 :(得分:0)

如果您使用的是Linux,则可以使用stat or fstat

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);

会给你这个信息:

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

使用stat检查尺寸:

struct stat info;

if(stat(filepath, &info) < 0) {
    /* error */
}

if(info.st_size == 0) { 
    /* file is empty */
}

或使用fstat

int fd = open(filepath, O_RDONLY);
struct stat info;

if(fstat(fd, &info) < 0) {
    /* error */
}

if(info.st_size == 0) { 
    /* file is empty */
}

答案 2 :(得分:0)

您可以使用ftell

#include <stdio.h>

int get_file_size (char *filename) {
   FILE *fp;
   int len;

   fp = fopen(filename, "r");
   if( fp == NULL )  {
      perror ("Error opening file");
      return(-1);
   }
   fseek(fp, 0, SEEK_END);

   len = ftell(fp);
   fclose(fp);

   return(len);
}