【发布时间】:2011-11-09 23:52:34
【问题描述】:
我有一个程序遍历文件系统层次结构,列出二进制文件中的文件路径名,如下所示:
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)
{
struct list_rec t;
no_of_files = no_of_files+1;
t.seqno = no_of_files;
t.path_length = strlen(fpath);
t.file_path = malloc((sizeof(char)*t.path_length)+1);
strcpy(t.file_path,fpath);
fwrite(&t.seqno,sizeof(int),1,listoffiles);
fwrite(&t.path_length,sizeof(int),1,listoffiles);
fwrite(t.file_path,t.path_length,1,listoffiles);
free(t.file_path);
return 0;
}
int main(int argc, char *argv[])
{
listoffiles = fopen("/home/juggler/Examples/Traces/files.txt","r+b");
no_of_files = 0;
ftw(argv[1],list_the_files,20);
}
然后通过以下方式读取文件以从不同的程序中检查:
struct list_rec{
int seqno;
int path_length;
char *file_path;
};
FILE *listoffiles;
int main()
{
struct list_rec t;
listoffiles = fopen("/home/juggler/Examples/Traces/files.txt","rb");
if(!listoffiles)
{
printf("Unable to open file");
return 1;
}
while(fread(&t.seqno,sizeof(int),1,listoffiles)!=0)
{
printf("\n %d ",t.seqno);/*Log Record Number*/
fread(&t.path_length,sizeof(int),1,listoffiles);
printf(" %d",t.path_length);
t.file_path = malloc(sizeof(char)*t.path_length);
fread(t.file_path,t.path_length,1,listoffiles);
printf(" %s",t.file_path);
fflush(stdout);
}
}
我的问题是运行第二个程序的输出显示一些不需要的字符附加到一些文件路径如下:检查记录 51611 和 51617
51611 92 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/document6_new.pdf��
51612 99 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/proof with graph.tex.sav
51613 115 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/Operations beyond read and write.tex.bak
51614 107 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/singe version implementation.blg
51615 93 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/formalization1.pdf
51616 92 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/document6_new.texÉ…
51617 95 /media/New Volume/ March2010/June_2009/new latex_12 may 2009/cascading undone.tex
【问题讨论】:
标签: c linux string binaryfiles