【问题标题】:Fopen function returns null when given an existing path给定现有路径时,Fopen 函数返回 null
【发布时间】: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,但此处有效提醒。)

标签: c fopen


【解决方案1】:

您的代码中有几个问题:

一方面,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 中)。

【讨论】:

  • 关于:As another thing, fgets automatically null terminates strings. As such, directory_path[strlen(directory_path) - 1] = 0; is not needed. It may truncate the end of your path 不太正确。 OP 试图用 NUL 字节替换尾随换行符(由fgets() 读取)
  • 关于:char directory_file[PATH_LEN+sizeof(LOG_NAME)+1] = { 0 }; sizeof() 将返回指针的长度。声明应为:char directory_file[PATH_LEN+strlen(LOG_NAME)+1] = { 0 };
  • @user3629249 已更新。看起来怎么样?
  • @user3629249 不,它将返回字符串的大小(包括终止的空字节)加上一个字符(用于反斜杠路径分隔符)。这是存储输入的最大可能路径所需的最小数量。
  • @user3629249 继续阅读sizeof:如果它传递了一个数组(恰好是字符串字面量),那么它会返回数组的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多