0

Hi I have some C++ code that uses user defined input to generate file-names for some output files:

std::string outputName = fileName;
for(int i = 0; i < 4; i++)
{
    outputName.pop_back();
}
std::string outputName1 = outputName;
std::string outputName2 = outputName;
outputName.append(".fasta");
outputName1.append("_Ploid1.fasta");
outputName2.append("_Ploid2.fasta");

Where fileName could be any word the user can define with .csv after it e.g. '~/Desktop/mytest.csv'

The code chomps .csv off and makes three filenames / paths for 3 output streams.

It then creates them and attempts to open them:

std::ofstream outputFile;
outputFile.open(outputName.c_str());
std::ofstream outputFile1;
outputFile1.open(outputName1.c_str());
std::ofstream outputFile2;
outputFile2.open(outputName2.c_str());

I made sure to pass the names to open as const char* with the c_str method, however if I test my code by adding the following line:

std::cout << outputFile.is_open() << " " << outputFile1.is_open() << " " << outputFile2.is_open() << std::endl;

and compiling and setting fineName as "test.csv". I successfully compile and run, however,

Three zeros's are printed to screen showing the three filestreams for output are not in fact open. Why are they not opening? I know passing strings as filenames does not work which is why I thought conversion with c_str() would be sufficient.

Thanks, Ben W.

SJWard
  • 3,629
  • 5
  • 39
  • 54

1 Answers1

2

Your issue is likely to be due to the path beginning with ~, which isn't expanded to /{home,Users}/${LOGNAME}.

This answer to How to create a folder in the home directory? may be of use to you.

Unfortunately, there is no standard, portable way of finding out exactly why open() failed:

I know passing strings as filenames does not work which is why I thought conversion with c_str() would be sufficient.

std::basic_ofstream::open() does accept a const std::string & (since C++11)!

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247