gpt4 book ai didi

c++ - 写入文件(如果是第一次创建)

转载 作者:行者123 更新时间:2023-11-28 02:33:50 24 4
gpt4 key购买 nike

我只想在第一次创建文件时将 Some Header 写入我的文件。文件名为报告.txt

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

   if(ifstream("report.txt")){
printf("The file already exists");

}

else
{
printf("file is created for first time\n");
ofstream resfile("report.txt");
resfile<<"MaxPackets\tInterval\tPacketSize\ttimeFirstTPacket"<<endl;

}

当它发生但没有任何内容被写入时,我得到输出“文件是第一次创建”。对不起,在我注释掉它后面的所有代码后,所有它都被写入文件。

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

   ofstream outfile("report.txt");
while(getline(infile,data))
{
istringstream res(data);
string word;
int flag;

if(line==0){

outfile<<"1000\t0.01\t64\t";

flag=0;

while(res>>word){

if(flag==1)
outfile<<word<<endl;

flag++;
}


}





line++;

}

outfile.close();

可是怎么改正呢??请帮忙

最佳答案

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

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

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

关于c++ - 写入文件(如果是第一次创建),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com