【问题标题】:Files become zero bytes after stat()stat() 后文件变为零字节
【发布时间】:2011-11-30 19:17:23
【问题描述】:

我在列出仅是目录或常规文件的子树中的文件时遇到了一个奇怪的问题。列出了这些文件,但在以下程序遍历它们之后文件的大小变为零。我该如何防止呢?是因为stat()吗?

struct list_rec{
    int seqno;
    int path_length;
    char *file_path;
};
FILE *listoffiles;
int no_of_files;/*couter to keep track of files visited*/
static int list_the_files(const char *fpath,const struct stat *sb, int tflag, struct FTW *ftwbuf)
{
  int fd;
  struct list_rec t;
  struct stat buff;

  if(stat(fpath,&buff) == -1)
 printf("Error reading inode");

  /*the file will be listed if it is directory or if it is a regular file and can be   opened for writing*/
  if(S_ISDIR(buff.st_mode)==0)
  {
 //printf("\nIT IS NOT A DIRECTORY %s",fpath);
if(S_ISREG(buff.st_mode)!=0)
{
    //printf("IT IS A REGULAR FILE %s",fpath);
    fd = open  (fpath,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
    if(fd != -1)
    {
        close(fd);
        no_of_files = no_of_files+1;
        t.seqno = no_of_files;
        t.path_length = strlen(fpath)+1;
        t.file_path = malloc(sizeof(char)*t.path_length);
        strcpy(t.file_path,fpath);

        fwrite(&t.seqno,sizeof(int),1,listoffiles);
        fwrite(&t.path_length,sizeof(int),1,listoffiles);
        fwrite(t.file_path,sizeof(char)*t.path_length,1,listoffiles);

        free(t.file_path);
    }
    else
        printf("\n is regular but could not open %s",fpath);
}
else
    printf("\nNot a regular file %s",fpath);    
 }
 else
 {
    no_of_files = no_of_files+1;
t.seqno = no_of_files;
t.path_length = strlen(fpath)+1;
t.file_path = malloc(sizeof(char)*t.path_length);
strcpy(t.file_path,fpath);

fwrite(&t.seqno,sizeof(int),1,listoffiles);
fwrite(&t.path_length,sizeof(int),1,listoffiles);
fwrite(t.file_path,sizeof(char)*t.path_length,1,listoffiles);

free(t.file_path);
  }
 return 0;
 }

 int main(int argc, char *argv[])
 {
   listoffiles = fopen("/home/juggler/files.txt","w+b");
   no_of_files = 0;
   ftw(argv[1],list_the_files,20);
   fwrite(&no_of_files,sizeof(int),1,listoffiles);//Writing the total number of    records at the end of the file
  }

谢谢。非常感谢您的帮助

【问题讨论】:

    标签: c linux file


    【解决方案1】:

    您正在使用 O_WRONLYO_TRUNC 打开文件,这会将文件截断为 0 长度。你可能只想要O_RDONLY

    【讨论】:

      【解决方案2】:

      不,这是因为您使用O_TRUNC 打开文件,这会将其截断为零字节。

      如果要检查是否可以打开文件进行写入,请使用:

      if (access(fpath, W_OK) == 0) {
          /* file can be opened for writing */
      

      【讨论】:

        猜你喜欢
        • 2020-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        • 1970-01-01
        • 1970-01-01
        • 2014-04-24
        相关资源
        最近更新 更多