Home > Software design >  Phantom \.txt file in windows
Phantom \.txt file in windows

Time:10-01

It seems like it is possible to create a file \.txt in windows that can be read, but I'm not able to access it any other way or see if it exists. This seems to only work for \.txt since I can't create other files with backslashes in it such as a\.txt

string filename = "\\.txt";

// make file
ofstream writer(filename);
writer << "This file exists" << endl;
writer.close();

// read file
ifstream reader(filename);
string line;
getline(reader, line);
cout << line << endl;
reader.close();

When I use ls -lia in bash, this file doesn't show up at all, but the program above reads it fine (I can remove the part that creates the file and run it later so the file does persists), how does this work?

CodePudding user response:

On Windows, ofstream writer("\\.txt") creates a file named .txt in the root of the current drive. It is a perfectly valid file name.

ofstream writer("a\\.txt") tries to create a file named .txt in the a subdirectory of the current directory. The a directory must exist in order for it to succeed. Most likely it does not exist, therefore it fails for you.

To create a directory you can use either the mkdir function (which has compatibility problems with other OSes because Windows is not POSIX compatible), or the CreateDirectory WINAPI function, that is Windows specific. After calling CreateDirectoryA("a"), the "a\\.txt" path should work.

  • Related