gpt4 book ai didi

c - 在字符串写入二进制文件期间写入不需要的字符

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:48 26 4
gpt4 key购买 nike

我有一个程序遍历文件系统层次结构,列出二进制文件中的文件路径名,如下所示:

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

最佳答案

当您读回文件路径时,您并没有以空值终止它们。

您应该分配比字符串长度多一个字符的值,并将最后一个字符设置为 0(fread 不会为您这样做)。

关于c - 在字符串写入二进制文件期间写入不需要的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7297715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com