Create/manipulate file within a directory other than main.cpp

Asked

Viewed 502 times

1

This works, creates a file and puts what I want inside it:

#include <fstream>
#include <vector>

using namespace std;
int main() {
    ofstream arquivo;
    arquivo.open("arquivo.txt");
    vector<string> v;
    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");
    if(arquivo.is_open()){
        for(auto n: v) { arquivo << n << endl; }
    }
}

But this does not work, if I want to create a new file inside a folder called "folder", it does not give error, just does not create the file. Does absolutely nothing:

#include <fstream>
#include <vector>

using namespace std;
int main() {
    ofstream arquivo;
    arquivo.open("pasta/arquivo.txt");
    vector<string> v;
    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");
    if(arquivo.is_open()){
        for(auto n: v) { arquivo << n << endl; }
    }
}

1 answer

2

The error is time to open a file nonexistent for recording. The method call ofstream::open() creates a new file if it does not exist, but, does not create directories!

You can include more elaborate error handling using the macro errno of the standard library cerrno together with the function std::strerror() of the standard library cstring.

Let’s see how to understand the error:

#include <fstream>
#include <vector>
#include <cstring>
#include <cerrno>
#include <iostream>

using namespace std;

int main( void ) {
    ofstream arquivo;
    vector<string> v;

    arquivo.open("diretorio/arquivo.txt");

    if(!arquivo.is_open()) {
        cerr << "Erro abrindo o arquivo para gravacao: " << std::strerror(errno) << endl;
        return 1;
    }

    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");

    for(auto n: v) { arquivo << n << endl; }

    return 0;
}

Compiling:

$ g++ -std=c++11 teste.cpp -o teste

Exit:

Erro abrindo o arquivo para gravacao: No such file or directory

A non-standard but elegant alternative to solve your problem is to use the library boost::filesystem, that has a function called create_directories(), let’s see:

#include <fstream>
#include <vector>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <boost/filesystem.hpp>

using namespace std;

int main( void ) {
    ofstream arquivo;
    vector<string> v;

    boost::filesystem::create_directories("diretorio" );

    arquivo.open("diretorio/arquivo.txt");

    if(!arquivo.is_open()) {
        cerr << "Erro abrindo o arquivo para gravacao: " << std::strerror(errno) << endl;
        return 1;
    }

    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");

    for(auto n: v) { arquivo << n << endl; }

    return 0;
}

Compiling:

$ g++ -lboost_system -lboost_filesystem -std=c++11 teste.cpp -o teste

Browser other questions tagged

You are not signed in. Login or sign up in order to post.