文件在stat()之后变为零字节

时间:2011-11-30 11:12:05

标签: c linux file

我在子树中列出只有目录或常规文件的文件时遇到了一个奇怪的问题。列出了文件,但是在以下程序遍历它们之后文件的大小变为零。我该如何预防呢?是因为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
  }

感谢。将非常感谢帮助

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

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

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

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