2013-05-18 44 views
0

我想在与当前目录相关的给定路径中创建文件。以下代码行为不正常。我有时看到创建的文件,有些时候看不到。这可能是因为当前目录中的更改。这是代码。在Linux中使用C++在给定路径创建文件

//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,我还没有看到创建的文件。

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

回答

3

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; 
} 
相关问题