How do I output into a file in subdirectory?

  c++, fstream, stringstream

This is not a duplicate. I’m trying to print some output to a file in a subdirectory (in this case to a file /stuff/output_1.txt) but it doesn’t seem to create any new file. The code executes but no file is created, nor any subdirectory called /stuff. Here is my code:

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

int main(void)
{
  int out = 1;
  stringstream fname;
  fstream f;
  fname << "./stuff/output" << "_" << out << ".txt";
  f.open(fname.str().c_str(), ios_base::out);
  f << "hello" << "t";
  f << endl;
  f.close();
}

When I instead use the line

fname << "output" << "_" << out << ".txt";

It creates a file called output_1.txt in the current directory so the rest of the code clearly works. What is going wrong?

I’m on macOS so the "/" should be correct instead of the "" used on Windows, no?

Source: Windows Questions C++

LEAVE A COMMENT