【问题标题】:Create a file at a given path using C++ in Linux在 Linux 中使用 C++ 在给定路径创建文件
【发布时间】:2013-05-13 19:00:50
【问题描述】:

我想在相对于当前目录的给定路径上创建一个文件。以下代码行为异常。我有时会看到创建的文件,有时却没有。这可能是因为当前目录发生了变化。这是代码。

//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();

现在,问题是文件仅在某些情况下创建。那就是当我将当前目录中的输入文件作为命令行参数时,它可以正常工作。

./program input_file

如果我有这样的东西,它不起作用

./program ./folder1/input_file

我尝试将完整路径作为ofstream 的参数,但我仍然看不到创建的文件。

这样做的正确方法是什么?谢谢

【问题讨论】:

    标签: c++ linux file path


    【解决方案1】:

    ofstream 不会在文件路径中创建缺少的目录,您必须确保目录存在,如果不使用操作系统特定的 api 或boost's file system library 创建它们。

    随时查看IO操作结果,查询系统错误码判断失败原因:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-09
      • 2020-08-10
      • 1970-01-01
      • 2017-07-17
      • 2022-07-27
      • 2017-08-06
      • 1970-01-01
      相关资源
      最近更新 更多