gpt4 book ai didi

c++ - fopen() 在内部更改我的文件名?

转载 作者:行者123 更新时间:2023-11-30 20:50:25 32 4
gpt4 key购买 nike

我在我的 C++ 程序中使用 fopen() 并尝试打开 .aff 文件。

我想解析一个名为 car_wheel.aff 的文件,在 if(ifp=fopen(path,"r")) 执行后,似乎 fopen() 函数更改了我的 path 变量???

我在评论中添加了我的问题的一些详细信息。

code(由于变量path是我的代码构造的,所以我把整段代码放在这里,可能看起来有点多余。)

    char* dir = "../kitchen/";
char filename[100];
char* path;
FILE *ifp;
int detail_level;
if(fscanf(fp,"%d %s",&detail_level,filename)!=2)
{
printf("Error: could not parse include.\n");
exit(0);
}

path = (char*)malloc(strlen(dir)+strlen(filename));
strcpy(path, dir);
strcat(path, filename); // path is "../kitchen/car_wheel.aff"
if(detail_level<=gDetailLevel)
{
if(ifp=fopen(path,"r"))
{
viParseFile(ifp);
fclose(ifp);
}
else
{
// jumped here and path became "../kitchen/car_wheel.aff1\002"
if (ifp == NULL) {
perror(path);
exit(EXIT_FAILURE);
}
printf("Error: could not open include file: <%s>.\n",filename);
exit(1);
}
}

我在我的IDE中调试了代码,它给出的文件名字符数组是 enter image description here

并且我的filename变量后面没有'1\002'。发生了什么事??

最佳答案

问题出在这里:

path = (char*)malloc(strlen(dir)+strlen(filename));

您没有为终止零字符分配空间。将其更改为:

path = (char*)malloc(strlen(dir)+strlen(filename)+1);

关于c++ - fopen() 在内部更改我的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45542508/

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