【发布时间】: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 好的,抱歉。