c - 当使用字符串变量作为路径时,fopen() 为 null

标签 c fopen

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/

相关文章:

c - 从加速度计检测运动

c - 使用原始套接字时,为什么需要给出两次 MAC 地址?

C编程: reading and writing binary files

c - 文件描述符的目的是什么?

创建一个文本文件,其中文件名基于一个或两个数组中的值

c - fopen - C 中作为流数据的原始数据

c - C 中的 fopen 和 fprintf 没有按预期工作?

c - 我怎样才能重现这个 DDD 测试?

c - 如何启用两个对象的不同 GL_POSITION

Collapse 子句在#pragma omp for 中被忽略