user592748
user592748

Reputation: 1234

Create a file at a given path using C++ in Linux

I want to create a file at a given path that is relative to the current directory. The following code behaves erratically. I some times see the file created and some times do not. That may be because of the change in the current directory. Here's the code.

//for appending timestamp
timeval ts;
gettimeofday(&ts,NULL);
std::string timestamp = boost::lexical_cast<std::string>(ts.tv_sec);
//./folder/inner_folder is an existing directory
std::string filename = "./folder/inner_folder/abc_"+timestamp+ ".csv";
std::ofstream output_file(filename);
output_file << "abc,efg";
output_file.close();

Now, the problem is the file is created only in some cases. That is when I have as a command line argument an input file from the current directory, it works fine.

./program input_file

If I have something like this, it does not work

./program ./folder1/input_file

I tried giving the full path as an argument for ofstream, I still don't see the files created.

What is the correct way to do this? Thanks

Upvotes: 0

Views: 1496

Answers (1)

hmjd
hmjd

Reputation: 121971

ofstream will not create missing directories in the file path, you must ensure the directories exist and if not create them using OS specific api or boost's file system library.

Always check the result of IO operations, and query system error code to determine reason for failures:

if (output_ file.is_open())
{
    if (!(output_file << "abc,efg"))
    {
        // report error.
    }
}
else
{
    const int last_error = errno;
    std::cerr << "failed to open "
              << filename
              << ": "
              << strerror(last_error)
              << std::endl;
}

Upvotes: 3

Related Questions