2

I'm trying to output data to a .csv file, but when I run the program it does not change the output file. It is as if I have not run the program at all. It builds successfully.

I created this project in XCode. The ".xcodeproject" and "example.csv" files are located in the working directory (Desktop -> ofstream). "main.cpp" is located in Desktop -> ofstream -> ofstream and is the only file in that folder. I am using "Release" for builds.

#include <iostream>
#include <fstream>

int main( int argc, char* argv[] )
{
    std::ofstream myfile;
    myfile.open ("example.csv");
    myfile << "This is the first cell in the first column.\n";
    myfile << "a,b,c,\n";
    myfile << "c,s,v,\n";
    myfile << "1,2,3.456\n";
    myfile << "semi;colon";
    myfile.close();
    return 0;
}

What am I missing to successfully write into this .csv file?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • "What am I missing to successfully write into this .csv file?" I'm not sure. What exactly is the problem you're having? Could you be more specific? –  May 15 '19 at 23:02
  • Either `myfile.open ("example.csv");` is failing, which you are not checking for, or the Current Working Directory of the calling process is not what you are expecting, so `"example.csv"` gets written in some other folder. You should never use relative file paths, always use absolute paths. And add error checking. – Remy Lebeau May 15 '19 at 23:03
  • Check that the call to `open()` worked ( add `if (myfile) {std::cerr << "Error\n";}`). If you are using an IDE it will "probably" be run in the same directory as the IDE (so look there for the 'example.csv'). You can try specifying a full path "/tmp/example.csv" or you can change the current working directory. https://stackoverflow.com/questions/3485166/change-the-current-working-directory-in-c – Martin York May 15 '19 at 23:33
  • 1
    Using an absolute file path fixed the issue. Thank you all – Garrett Jennings May 15 '19 at 23:58
  • Unable to reproduce problem. The code compiled, created and wrote the expected 5 lines of content ... the location of the new file is the default directory where the code was compiled and run. – 2785528 May 15 '19 at 23:58

0 Answers0