【问题标题】:C++ Change output file name if exists [duplicate]C ++如果存在则更改输出文件名[重复]
【发布时间】:2017-04-12 17:45:30
【问题描述】:

我正在尝试编写 HTML 输出文件。该文件已写入,一切都很好,但我想知道是否有办法获取带有文件名的字符串,检查它是否存在,如果是,则以某种方式更改该字符串。所以我永远不会覆盖已经存在的文件。

string outputFile;
cin>>outputFile;
ofstream out;
string path ="..\\data\\"+ outputFile+ ".html";
out.open(path.c_str());

所以在这种情况下,如果 outputFile 是让我们说“耶稣”,那么我想做一些事情,所以如果我运行 3 次,我会得到类似 Jesus.html、Jesus2.html、Jesus3.html 的东西。不一定要这样编号,只要对该字符串进行任何更改即可。这甚至可能吗?我试过这个 tmpnam() 但我真的不明白它应该如何工作以及它是否可以使用。

感谢您的帮助

【问题讨论】:

    标签: html c++ output ostream


    【解决方案1】:

    您可以使用此处提到的方法之一检查文件是否存在:

    Fastest way to check if a file exist using standard C++/C++11/C?

    完整的代码如下所示

    inline bool file_exists (const std::string& name) {
      struct stat buffer;   
      return (stat (name.c_str(), &buffer) == 0); 
    }
    
    while (file_exists(file_name))
        file_name += "_1";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 2014-07-20
      • 2018-08-02
      • 2014-01-04
      • 2011-11-05
      • 2021-06-24
      相关资源
      最近更新 更多