如果文件存在,则使用它,如果不存在,则创建它。

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.

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

你好,我希望从我的程序中检查文件是否已经存在,所以程序会在文件存在时打开它,然后我可以在其中写入内容。如果文件未打开(以前未创建),则程序会创建它。问题是当我创建一个 .csv 文件并完成写入后,我想检查所写的内容是否真的存在,但是文件无法打开,在 .txt 文件中,所有内容都是空白的。


1
请参考相关问题:https://dev59.com/XGcs5IYBdhLWcg3wh0f7。 - Mihai8
当您完成if块中的datoteka时,文件将关闭。原始代码块之外从未打开过该文件,因此您对那个所做的任何事情实际上都不会“做”任何事情。(我只能想象您没有发布的未经检查的IO)无论如何,if块中的datoteka有什么意义呢? - WhozCraig
2个回答

13

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

7
如果文件名不存在,将创建该文件。否则,如果使用 fstream::app,则在文件 filename 已经存在的情况下,将数据追加到文件中而不是覆盖它。
int writeOnfile (char* filetext) {
       ofstream myfile;
       myfile.open ("checkSellExit_file_output.csv", fstream::app);
       myfile << filetext;
       myfile.close();
       return 0;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接