13
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 it should do is create a file if it was not created before, and if it is created write into that file.

Hello there, so what I wanted from my program is that it check if the file already exists, sothe program open if it does and I can write in it, if the file is not opened(have not been created before) the program create it. So the problem is when I create a .csv file, and finish writing and I wanted to check if the written is really there, the file cannot be opened. In .txt file, everything is blank.

Kryston
  • 155
  • 1
  • 2
  • 6
  • 1
    See related question http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c. – Mihai8 May 31 '14 at 07:44
  • When you're done with the `datoteka` in the if-block the file is closed. The original outside the if-block was never opened, so anything you're do to *that* doesn't actually "do" **anything**. (I can only imagine the unchecked IO you didn't post) What is the point of the `datoteka` in the if-block anyway? – WhozCraig May 31 '14 at 07:53

2 Answers2

13

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

#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;
}
Software_Designer
  • 8,490
  • 3
  • 24
  • 28
7

If filename does not exist, the file is created. Otherwise, the fstream::app, If file filename already exists, append the data to the file instead of overwriting it.

int writeOnfile (char* filetext) {
       ofstream myfile;
       myfile.open ("checkSellExit_file_output.csv", fstream::app);
       myfile << filetext;
       myfile.close();
       return 0;
    }