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

c++ - fopen() internally changes my filename?

我在我的 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[=10=]2"
            if (ifp == NULL) {
                perror(path);
                exit(EXIT_FAILURE);
            }
            printf("Error: could not open include file: <%s>.\n",filename);
            exit(1);
        }
    }

我调试了 ide 中的代码,它给出的文件名字符数组是

而且我的 filename 变量后面没有 '1[=18=]2'。发生什么事了??

问题在这里:

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

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

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