If the file exists, work with it; if not, create it

fstream datoteka;
datoteka.open("Informacije.txt",  fstream::in | fstream::out | fstream::app);

if(!datoteka.is_open()){              
    ifstream datoteka("Informacije.txt")
    datoteka.open("my_file.txt", fstream::in | fstream::out | fstream::app);
}/*I'm writing IN the file outside of that if statement.

So what he should do is create a file if it has not been created before, and if it was created, write to this file.

Hello, so what I want from my program is to check if the file already exists, sothe program open, if it exists, and I can write in it if the file is not open (have not been created before ), the program will create it. Therefore, the problem is when I create the CSV file and finish recording, and I wanted to check if it was really written, the file could not be opened. Everything is empty in the .txt file.

+4
source share
1 answer

datoteka.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);  works great.

#include <fstream>
#include <iostream>
using namespace std;

int main(void)
{

     char filename[ ] = "Informacije.txt";
     fstream appendFileToWorkWith;

     appendFileToWorkWith.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);


      // If file does not exist, Create new file
      if (!appendFileToWorkWith ) 
      {
        cout << "Cannot open file, file does not exist. Creating new file..";

        appendFileToWorkWith.open(filename,  fstream::in | fstream::out | fstream::trunc);
        appendFileToWorkWith <<"\n";
        appendFileToWorkWith.close();

       } 
      else   
      {    // use existing file
         cout<<"success "<<filename <<" found. \n";
         cout<<"\nAppending writing and working with existing file"<<"\n---\n";

         appendFileToWorkWith << "Appending writing and working with existing file"<<"\n---\n";
         appendFileToWorkWith.close();
         cout<<"\n";

    }




   return 0;
}
+5

Source: https://habr.com/ru/post/1542746/


All Articles