写入文件(如果文件是首次创建)
Writing to a file if it's being created for first time
我想只在第一次创建文件时将一些标头写入我的文件。 文件名为报表.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);
这将使它附加到文件的末尾,而不是覆盖它。
相关文章:
- 终端不会为C++文件创建.exe文件吗
- 如何从具有两列的.txt文件创建并行数组?
- 从 .lib 文件创建一个.dll文件
- 如何从输入文件 c++ 创建随机名称生成器
- 无法从 cso 文件创建顶点着色器(从 fx 文件创建)
- 如何为多个目录中的多个文件创建生成文件?
- 在编译时从 c++ 文件创建枚举
- 如何在运行时从 c++ 中的 DLL 文件创建对象?
- 文件创建并不总是成功
- 如何使用 QFile、c++ 从文件创建整数数组
- 您可以使用 makefile 从 .o 对象文件创建 C++ 文件吗?
- 从函数中的dat文件创建一个2维数组
- 如何为 cpp 和 h 文件创建别名(并忽略编译器__attributes__)
- 如何从现有的生成文件创建 CMake 文件?
- 为什么我无法使用文本文件创建文件映射?
- 通过读取文件创建映射<字符串,矢量>时如何管理内存<string>
- 从文本文件创建 2D 字符串矢量
- ofStream: - 尽管文件创建了,但文本文件上没有输出
- 从语言文件创建JSON对象
- 将文本文件创建到节点.js的插件C++