当使用字符串变量作为路径时,fopen() 为 null
fopen() is null when using a string variable as path
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()
查看失败的原因。
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()
查看失败的原因。