【问题标题】:C fopen() - Possible issue with absolute path [duplicate]C fopen() - 绝对路径的可能问题[重复]
【发布时间】:2016-04-06 15:00:48
【问题描述】:

我目前在 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");

任何帮助将不胜感激。

【问题讨论】:

  • 您的路径是否包含任何空格或非 ASCII 符号?这可能是个问题
  • 不,路径只包含拉丁字母。
  • 停止使用默认为 MBCS (ANSI) 字符编码的工具。记录在案:这是 2016 年。
  • 不要修改您的问题,以免答案变得毫无意义。
  • @JonathanLeffler 好的,抱歉。

标签: c windows path fopen


【解决方案1】:

您正在返回getFileName 中的局部变量的地址,这会导致未定义的行为
这是 C 语言中的一个常见陷阱。

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

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

【讨论】:

  • “不起作用”没有任何意义,抱歉。您需要准确解释什么不起作用。在调用 fopen 之前打印出 fileName。
  • printf 样式调试不是调试代码的推荐方式。这是不合适的,因为运行代码不可避免地会产生副作用。应该使用调试器。
  • 首先,感谢您的回答。其次,恰好在 fopen 'fileName' 之前是 'C:\Users\etc\etc\input.txt'。我尝试再次将 '\' 替换为 '/'。我应该尝试使用双斜杠吗?
  • @M.Demo:好像您正在尝试打开一个文件,但您没有访问权限。
  • @M.Demo:如果一个答案不能解决你的问题,你不应该接受它。从您的 cmets 看来,这个答案似乎不能解决您的问题。
【解决方案2】:

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

而是从调用函数传递它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多