Search code examples
c++text-filesfopen

How to create a text file in subdirectory?


I need to create a text file in my program's subdirectory to write some data. The lines below do not work, the folder is not created. The file is not created even if I create the subfolder manually. Without subfolder in line this command works perfectly.

FILE* f;
if (fopen_s(&f, "/Sandbox/OUTPUT.txt", "w"))
   return 1; // Nothing happens
if (fopen_s(&f, "//Sandbox//OUTPUT.txt", "w"))
   return 1; // Nothing happens
if (fopen_s(&f, "\\Sandbox\\OUTPUT.txt", "w"))
   return 1; // Nothing happens
if (fopen_s(&f, "\Sandbox\OUTPUT.txt", "w"))
   return 1; // Nothing happens
if (fopen_s(&f, "Sandbox/OUTPUT.txt", "w"))
   return 1; // Nothing happens
if (fopen_s(&f, "Sandbox\OUTPUT.txt", "w"))
   return 1; // Creates a file named 'SandboxOUTPUT.txt'

How to code this correctly?


Solution

  • I suppose you're working in a Windows environment.

    In case the Sandbox folder is a subdirectory of the current directory, you should use "Sandbox\\OUTPUT.txt" or ".\\Sandbox\\OUTPUT.txt".
    If it's a folder within the root of the drive, then use "C:\\Sandbox\\OUTPUT.txt".

    In other words, a backslash needs to be escaped by means of another backslash.

    If you want to create the directory first, then try:

    mkdir(".\\Sandbox") or mkdir("C:\\Sandbox").