C fopen() - 绝对路径可能存在的问题

时间:2016-01-02 14:06:36

标签: c windows path fopen

我目前在Windows 10下使用Code :: Blocks 13.12(编译器:GNU GCC)。

我试图打开一个文件并加载其内容,但fopen给了我麻烦。 ' input.txt'存在于与我的可执行文件相同的目录中。我已经检查了权限。

获取路径的功能:

char* getFileName()                        
{         
    char *fileName; /* the path of the .txt file */
    char path[MAX_PATH];

   /* get the path of the executable */
   GetModuleFileName(NULL, path, MAX_PATH);
   /* remove the name of the executable from the path */
   PathRemoveFileSpec(path);
   /* check case where path is directory root */
   if(PathIsRoot(path))
       strcat(path, "\\*");

   /* add the name of the .txt file to the path */
   strcat(path, "\\input.txt");
   /* not sure if needed */
   path[strlen(path)] = '\0';
   fileName = strdup((char *) path);

   return fileName;
}

加载文件内容的功能:

bool loadDict(char *fileName)
{
    FILE *fp; /* file stream */
    char line[LINE_SIZE]; /* each line of the file */
    // other variables

    /* try to open file for reading */
    if((fp = fopen(fileName, "r")) == NULL)
    {
        fprintf(stderr, "Error: Could not open the file '%s' to read\n", fileName);
        return false;
    }

    // stuff done

    /* file is no longer needed, close it */
   if(fclose(fp))
   {
        fprintf(stderr, "Error: Could not close the file '%s' to read\n", fileName);
        return false;
   }
   return true; /* in case no problem has occured */
}

主:

int main()
{
    char *fileName;

    fileName = getFileName();
   /* try to load the dictionary into memory */
   if(!loadDict(fileName))
   {
       fprintf(stderr, "Error: The dictionary could be not loaded into memory.\nProgram terminating...\n");
       return 1;
   }

    // other stuff
    return 0;
}

我收到两个错误(无法打开文件,无法加载)。我已经尝试过替换' \'用' /'或使用双斜线但没有成功。

 FILE *fp = fopen("path\\input.txt", "r");

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

您将在getFileName中返回局部变量的地址,从而导致未定义的行为
这是C中常见的陷阱。

您需要:a)在堆上分配字符串(使用例如malloc)并将其返回。
B)让getFileName指向一个指针然后填充调用者分配的缓冲区。

此外,在调试此类问题时,不要只假设一切正常。在尝试printf之前,使用filename查看fopen的价值。

答案 1 :(得分:1)

您的数组path是一个局部变量,其范围仅限于函数getFileName。不要归还其地址。

而是从调用函数传递它。