【问题标题】:If file exist, work with it, if no, create it如果文件存在,则使用它,如果不存在,则创建它
【发布时间】:2014-07-20 23:41:03
【问题描述】:
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.

所以它应该做的是创建一个文件,如果它之前没有创建,如果它被创建,则写入该文件。

你好,所以我想从我的程序中检查文件是否已经存在,所以如果文件已经存在,程序就会打开,如果文件没有打开(还没有创建,我可以写入它)之前)程序创建它。所以问题是当我创建一个 .csv 文件并完成写入并且我想检查写入是否真的存在时,文件无法打开。在 .txt 文件中,一切都是空白的。

【问题讨论】:

  • 当你在 if 块中完成 datoteka 时,文件将关闭。 if 块之外的原始文件从未打开过,因此您对 that 所做的任何事情实际上都不会“做”anything。 (我只能想象你没有发布的未经检查的 IO)if 块中的datoteka 有什么意义?

标签: c++ file fstream


【解决方案1】:

datoteka.open(filename, std::fstream::in | std::fstream::out | std::fstream::app); 工作正常。

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

【讨论】:

    【解决方案2】:

    如果文件名不存在,则创建文件。否则, fstream::app,如果文件filename已经存在,将数据追加到文件而不是覆盖它。

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

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 1970-01-01
      • 2021-01-31
      • 2022-01-11
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多