【发布时间】:2019-05-28 20:44:57
【问题描述】:
当尝试使用 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");
}
我的程序一直有效,直到我尝试写入文件以创建日志文件。这意味着该路径毫无疑问是正确的。
谁能告诉我这里的问题?
【问题讨论】:
-
可能是访问权限的问题。您应该使用 perror() 来获得有意义的错误消息。
-
你输入了什么文件夹名?
-
查看文件夹中的文件权限。也可能是拼写问题。
-
始终检查 fgets() 的返回值: if (fgets(...) == NULL) /* 不确定数组 */ (复制其他评论的 Pasta,但此处有效提醒。)