fopen error due to long path gives no such file exist

720 Views Asked by At

I want to know whether fopen failed in C due to long path or file not exist

#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;
}

The first fopen has long path whereas the second one is short but file doesn't exist. For both these case output is similar:

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

Is there a way to know the difference?

1

There are 1 best solutions below

1
On

Call a routine using the extended-length path syntax; prefixing the path with \\?\.

To specify an extended-length path, use the "\\?\" prefix. For example, "\\?\D:\very long path".

In your case, the path would be

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

The same link goes on to describe a new feature in Windows 10, Version 1607

Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must opt-in to the new behavior.

To enable the new long path behavior, both of the following conditions must be met:

  • The registry key HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD) must exist and be set to 1. ...
  • The application manifest must also include the longPathAware element. ...