user840718 user840718 - 1 year ago 84
C++ Question

Write a file in a specific path in C++

I have this code that writes successfully a file:

ofstream outfile (path);

buffer and size are ok in the rest of code.
How is possible put the file in a specific path?

Answer Source

Specify the full path in the constructor of the stream, this can be an absolute path or a relative path. (relative to where the program is run from.

The the streams destructor close the file for you, explicit closes are MORE likely to introduce bugs (writing to after the file is close).

#include <fstream>
#include <string>

int main()
    const char *path="/home/user/file.txt";
    std::ofstream file(path); //open in constructor
    std::string data("data to write to file");
    file << data;
}//file destructor

Note you can use std::string in the file constructor in C++11 and is preferred to a const char* in most cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download