0

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?

Perotto
  • 194
  • 1
  • 14

2 Answers2

2

If you have a C++17 enabled compiler, make use of std::filesystem. Here's an introduction to some of the things you can do with it that should be pretty self-explanatory, but if anything is unclear, ask and I'll try to clarify.

#include <filesystem>
#include <fstream>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // create a path in an OS agnostic manner
    fs::path dir_path = fs::path(".") / "Sandbox";
    fs::directory_entry dir(dir_path);

    if(dir.exists()) {
        std::cout << dir << " already exists\n";
        if(dir.is_directory() == false) {
            std::cerr << "... but is not a directory\n";
            return 1;
        }
    } else {
        std::cout << "creating dir  " << dir << "\n";
        if(fs::create_directory(dir) == false) {
            std::cerr << "failed creating " << dir << "\n";
            return 1;
        }
    }
    {
        // create a path to your file:
        fs::path filename = dir_path / "OUTPUT.txt";
        std::cout << "creating file " << filename << "\n";

        std::ofstream os(filename);
        if(os)
            os << "Hello world.\n";
        else {
            std::cerr << "failed opening " << filename << " for writing\n";
            return 1;
        }
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

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").

Robert Kock
  • 5,795
  • 1
  • 12
  • 20