给定现有路径时,Fopen函数返回null

时间:2019-05-28 20:44:57

标签: c fopen

尝试使用fopen(path, "2");打开文件时,我在现有路径上得到NULL

iv'e试图仅输入文件名,但是可以,但是我希望程序在路径中写入文件... 是的,必要时,我用双反斜杠"\\"编写了路径。 是的,毫无疑问,这条路已经存在。

FILE* log;
char directory_path[PATH_LEN] = { 0 };
char directory_file[PATH_LEN] = { 0 };

//directory_path is the directory, entered by  the user
//LOG_NAME is the files name without the path - "log.txt"
//#define PATH_LEN 100

printf("Folder to scan:  ");
fgets(directory_path, PATH_LEN, stdin);
directory_path[strlen(directory_path) - 1] = 0;

//this section connects the path with the file name.
strcpy(directory_file, directory_path);
strcat(directory_file, "\\");
strcat(directory_file, LOG_NAME);

if ((log = fopen(directory_file, "w")) == NULL)
{
    printf("Error");
}

我的程序一直有效,直到我尝试写入文件以创建日志文件。这意味着路径无疑是正确的。

有人可以在这里告诉我问题吗?

1 个答案:

答案 0 :(得分:0)

您的代码中有几个问题:

其中之一,fopen(path, "2");无效。 mode参数需要包含arw中的一个,并且可以选择包含b+

另一方面,directory_path[strlen(directory_path) - 1] = 0;可能会截断路径的结尾(如果长度超过PATH_LEN个字符)。

由于将字符串复制到相同大小的缓冲区,然后将另外两个字符串连接到该缓冲区,因此缓冲区溢出也可能存在问题。因此,您应该更改此行:

char directory_file[PATH_LEN] = { 0 };

对此:

char directory_file[PATH_LEN+sizeof(LOG_NAME)+1] = { 0 };

要调试此问题,您应打印输入的字符串并在使用前要求确认(将其包装在#ifdef DEBUG中)。