char path[strlen(dictionary) + 3];
strcat(path, "./");
// dictionary is "dictionaries/large" char*
strcat(path, dictionary);
// dictionaryFile != NULL
FILE *dictionaryFile = fopen("./dictionaries/large", "r");
// dictionaryFile == NULL
FILE *dictionaryFile = fopen(path, "r");
if (dictionaryFile == NULL)
{
printf("Not success\n");
}
我正在尝试打开相对于 .c 文件当前目录的文件夹内的文件。
为什么当我使用路径变量时 fopen()
不起作用,但是当我直接传递目录时它起作用了?
最佳答案
char path[strlen(dictionary) + 3];
strcat(path, "./");
这里path
是未初始化的;而 strcat
期望它以空字节终止。请改用 strcpy
,例如:
char path[strlen(dictionary) + 3];
strcpy(path, "./");
但是,由于 fopen()
可能失败,您的代码中可能存在其他问题。检查 errno
并使用 perror()
看看失败的原因。
关于c - 当使用字符串变量作为路径时,fopen() 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47811219/