fopen没有在linux上工作,因为名字中包含德语字符的文件

时间:2012-10-19 10:13:34

标签: c linux unicode fopen

我在c中编写了一个代码,用于文件处理。文件名中包含一些德语字符。此代码在Windows上完美运行。但它不适用于Linux。 fopen正在提供“无法打开文件”错误。 我检查了文件路径,文件存在那里。此外,我已阅读该文件夹的写入权限。

代码如下。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    const char *fileName = "/users/common/haëlMünchen.txt";

    FILE * pFile;
    char errorMessage[256];
    pFile = fopen (fileName,"r");
    if (pFile != NULL)
    {
        fprintf (stdout,"fopen example",errorMessage);
        fclose (pFile);
    }
    else
    {
    sprintf(errorMessage, "Could not open file %s", fileName);
    fprintf(stdout, "%s\n", errorMessage);
    }
    return 1;
}

关于此的任何输入?

1 个答案:

答案 0 :(得分:4)

在Linux上,您可以用

替换sprintf来电
snprintf (errorMessage, sizeof(errorMessage), 
          "Could not open file %s - %m", fileName);

(一般提示是避免sprintf,因为可能存在缓冲区溢出,只使用snprintf

如果要避免使用GLibc特定的%m格式说明符,并使用更多标准函数,则代码

snprintf (errorMessage, sizeof(errorMessage), 
          "Could not open file %s - %s",
          fileName, strerror(errno)); 

并且不要忘记#include <errno.h>,并仔细阅读 errno(3)手册页。

顺便说一下,您可以避免同时执行snprintfprintf,只需编写代码

fprintf (stderr, "Cannot open file %s - %s\n",
        fileName, strerror(errno));

(错误报告通常会转到stderr,正如Jonathan提醒的那样)

然后再次运行您的程序。也许您在字符编码方面存在问题(在源文件或文件系统中)。

您还可以在程序中使用strace(或许ltrace)来了解它正在进行的实际系统调用。