C 使用字符串变量作为路径时,fopen()为空

C 使用字符串变量作为路径时,fopen()为空,c,fopen,C,Fopen,我正试图打开文件夹中与.c文件当前目录相关的文件 为什么当我使用path变量fopen时它不工作,但当我直接传递目录时它工作 char path[strlen(dictionary) + 3]; strcat(path, "./"); // dictionary is "dictionaries/large" char* strcat(path, dictionary); // dictionaryFile != NULL FILE *dictionaryFile = fopen("./di

我正试图打开文件夹中与.c文件当前目录相关的文件

为什么当我使用path变量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");
}
此处路径未初始化;而strcat希望它以空字节终止。请改用strcpy,例如:

char path[strlen(dictionary) + 3];
strcat(path, "./");

但是,您的代码中可能存在其他问题,因此fopen可能会失败。选中errno并使用查看失败的原因。

请尝试printf%s,path;或者只是FILE*dictionaryFile=fopenpath,r;perrorfopen您将很容易看到错误。字符路径[strEndictionary+3]=;将确保字符串的初始化,并允许您在其中使用strcat。如果您在未初始化的缓冲区上使用strcat,您可以通过打印路径或使用调试器来了解自己。@usr没错,他在那里使用strlen。不管怎样,初始副本上的strcpy更好。或者只是char路径[strndictionary+3]=。/;字符路径[strlendictionary+3]=./;我得到这个错误:可变大小的对象可能没有初始化。但除此之外,第一种解决方案是有效的。我忘了VLAs不能初始化。那么你就得用strcpy了。
char path[strlen(dictionary) + 3];
strcpy(path, "./");