If file exist, work with it, if no, create it

后端 未结 2 1660
独厮守ぢ
独厮守ぢ 2021-01-05 09:23
fstream datoteka;
datoteka.open(\"Informacije.txt\",  fstream::in | fstream::out | fstream::app);

if(!datoteka.is_open()){              
    ifstream datoteka(\"Inf         


        
2条回答
  •  伪装坚强ぢ
    2021-01-05 09:46

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

    #include 
    #include 
    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 "<

提交回复
热议问题