使用fstream创建文件,如果它不存在利用seekp / seekg?

时间:2015-10-21 08:40:49

标签: c++ fstream seekg

fstream file(file_1.c_str(), ios::out | ios::in | ios::ate); //convert string to const char*

如果文件不存在则出错。 if ( ! file ) = true

fstream file(file_1.c_str(), ios::out | ios::in | ios::app); //convert string to const char*

使用ios::app seekg& seekp功能不起作用。 file.seekg(4, ios_base::beg);

我想:

  1. USER输入文件名
  2. 如果不存在则创建文件
  3. 使用seekg& seekp;
  4. 如果再次运行程序,请不要删除该文件。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要这样的东西:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    string name;
    std::cin>>name;
    std::ofstream file (name.c_str());
    outfile << "Text in file." << std::endl;
    file.close();
    return 0;
}
相关问题