Search code examples
c++visual-studio-2012printingdirectoryofstream

Cannot write to a folder within the exectuable's current directory


I have a program that I'm attempting to write various files to. In an attempt to clean it up I would like to put these files into a directory. My program is running in a directory different from the sln for VS 2012 i.e. the exe is the only part of the VS files in the directory. If I simply print the files, it's fine but if I attempt to print those same files to a different directory, then it doesn't do anything. I printed out the directory that I'm attempting to access and I'm getting "000000" as a response. code looks like:

std::ofstream output
output.open("\myFiles\entityOutput.csv", std::ios::app);
output << "print some stuff here" << std::endl; 

I'm sure it's something simple but I haven't been able to figure out what. Tried "\\myFiles....." already "/myFiles" etc. I'm on a Windows 7 system as well.


Solution

  • That's because, while opening a file, you need to swap \ with either \\ or /. The reason is that \ character is considered as a special one that's used for example to represent end of line character (\n).

    Just swap output.open("\myFiles\entityOutput.csv", std::ios::app); to output.open("/myFiles/entityOutput.csv", std::ios::app);, however make sure that the path is also correct!

    Usually it's a good programming practice to check whether or not a file opening succeeded at first.