代码之家  ›  专栏  ›  技术社区  ›  TQL

将字符串变量用作路径时,fopen()为null

  •  0
  • TQL  · 技术社区  · 7 年前
    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文件。

    为什么当我使用path变量时 fopen() 不工作,但当我直接传递目录时,它工作吗?

    1 回复  |  直到 7 年前
        1
  •  8
  •   P.P    7 年前
    char path[strlen(dictionary) + 3];
    strcat(path, "./");
    

    在这里 path 未初始化;鉴于 strcat 应以空字节终止。使用 strcpy 相反,例如:

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

    但是,您的代码中可能存在其他问题 fopen() 可能会失败。检查 errno 和使用 perror() 看看它为什么失败。