【问题标题】:fopen error due to long path gives no such file exist由于长路径导致的 fopen 错误不存在此类文件
【发布时间】:2020-07-08 05:37:34
【问题描述】:

我想知道fopen是否由于路径长或文件不存在而在C中失败

#include<stdio.h>
#include <errno.h>
extern int errno ;
int main(){
FILE *p;
int errnum;
p=fopen("C:\\Users\\kkm\\testtttttttttttttttttttttttttttttttttttttt\\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\\ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\\b.txt","w");
//p=fopen("C:\\Users\\kkm\\testtttttttttttttttttttttttttttttttttttttt\\xxxx.txt","r");
if (p == NULL) {

      errnum = errno;
      fprintf(stderr, "Value of errno: %d\n", errno);
      perror("Error printed by perror");
      fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
   } else {

      fclose (p);
   }
return 0;
}

第一个 fopen 路径很长,而第二个 fopen 很短但文件不存在。 对于这两种情况,输出是相似的:

Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory

有没有办法知道区别?

【问题讨论】:

  • 文件夹路径是否存在? fopen 要求文件夹存在且可用。 “为 fopen 构建路径时,请确保驱动器、路径或网络共享在执行环境中可用。”
  • MS 报告的“路径不存在”与“路径太长”的错误相同。在调用fopen 之前,您可以轻松检查路径是否太长。 (类似于“我分配了多少内存?”A:你告诉它分配的数量。)
  • 是的文件夹存在。我认为检查文件大小然后进行 fopen 不会很好。最好是 fopen 返回什么错误,然后进行相应处理。

标签: c fopen file-handling long-filenames


【解决方案1】:

使用extended-length path 语法调用例程;在路径前加上 \\?\

要指定扩展长度的路径,请使用“\\?\”前缀。例如,“\\?\D:\很长的路径”。

在你的情况下,路径是

"\\\\?\\C:\\Users\\kkm\\testtttttttttttttttttttttttttttttttttttttt\\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\\ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\\b.txt"

same link 继续描述 Windows 10 版本 1607 中的一项新功能

从 Windows 10 版本 1607 开始,MAX_PATH 限制已从常见的 Win32 文件和目录函数中删除。但是,您必须选择加入新行为。

要启用新的长路径行为,必须同时满足以下两个条件:

  • 注册表项HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD) 必须存在并设置为1。...
  • 应用程序清单还必须包含longPathAware 元素。 ...

【讨论】:

  • Hi Dan 感谢您提供扩展长度路径解决方案。有没有办法知道错误有一个枚举ENAMETOOLONG,你知道吗?这里可以用吗?
猜你喜欢
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多