写入文件(如果文件是首次创建)

Writing to a file if it's being created for first time

本文关键字:文件 创建 如果      更新时间:2023-10-16

我想只在第一次创建文件时将一些标头写入我的文件。 文件名为报表.txt

到目前为止,我的尝试-->

   if(ifstream("report.txt")){
       printf("The file already exists");
   }
 else
 {
     printf("file is created for first timen");
    ofstream resfile("report.txt");
       resfile<<"MaxPacketstIntervaltPacketSizettimeFirstTPacket"<<endl;
 }

它发生时,我得到输出"文件是第一次创建的",但没有写入任何内容。抱歉,在我注释掉它之后存在的所有代码后,它都被写入了文件。

上面几行后面的代码是 -->

   ofstream outfile("report.txt");
    while(getline(infile,data)) 
     {
         istringstream res(data);
              string word;
              int flag;
         if(line==0){
              outfile<<"1000t0.01t64t";
              flag=0;
              while(res>>word){
                  if(flag==1)
                    outfile<<word<<endl;
                flag++;
              }

         }


         line++;
     }
     outfile.close();

但是如何纠正它?? 请帮忙

您打开文件进行输出两次,第二次是覆盖第一次编写的内容。您可以只打开一次,也可以第二次以追加模式打开它:

ofstream outfile("report.txt", std::ios::app);

这将使它附加到文件的末尾,而不是覆盖它。