How to create a file in another directory in C ++?

#include <iostream>
#include <fstream>
#include <cstdlib>

int main() {
    std::fstream f1("/tmp/test");
    if (!f1) {
        std::cerr << "f1 failed\n";
    } else {
        std::cerr << "f1 success\n";
    }
    FILE *f2 = fopen("/tmp/test", "w+");
    if (!f2) {
        std::cerr << "f2 failed\n";
    } else {
        std::cerr << "f2 success\n";
    }
}

Creating a file in / tmp / does not work for me with fstream, but with fopen. What could be the problem? (I get f1 unsuccessfully and f2 success when / tmp / test does not exist yet)

+3
source share
3 answers

You have to say that you open the file for output, like this

std::fstream fs("/tmp/test", std::ios::out);

Or use a stream instead of fstream, which by default opens a file for output:

std::ofstream fs("/tmp/test");
+4
source

Your first method call does not automatically create the file: see fstream .

If you want your first method call to create a file, use:

std::fstream f1("/tmp/test", fstream::out);
0
source

, fstream, ,

std::fstream f1("/tmp/test", std::fstream::in | std::fstream::out);

,

0
source

Source: https://habr.com/ru/post/1724686/


All Articles