Search code examples
c++cfileiofopen

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


I use fopen() in my c++ program and I tried to open a .aff file.

I want to parse a file named car_wheel.aff and after if(ifp=fopen(path,"r")) has executed, it seems the fopen() function changes my path variable???

I add some detail to my question to the comment.

code (since variable path is constructed by my code, I put the whole piece of code here, which may seem a bit redundant.)

    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);
        }
    }

I debugged the code in my ide, and it gave the filename char array is enter image description here

and there is no '1\002' behind my filename variable. What happened??


Solution

  • The problem is here:

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

    You don't allocate space for the terminating zero character. Change it to this:

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