Search code examples
c++fstreamseekg

Create file using fstream if it doesn't exist that utilizes seekp/seekg?


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

Error if File does not exist. if ( ! file ) = true

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

using ios::app seekg & seekp functions not working. file.seekg(4, ios_base::beg);

I would like to have:

  1. USER input file name
  2. create file if NON existing
  3. use seekg & seekp;
  4. Not remove the file if you run the program again.

Solution

  • If I understand you correctly, you need something like this:

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