#include <iostream>
#include <fstream>
#include <graphics.h>
using namespace std;
int c;
fstream file("happy.txt");
int main()
{
file.open("happy.txt", fstream::out|fstream::in|fstream::trunc );
file.close(); //to clear the file first
initwindow(1000,600);
while (true){
c = getch();
file.open("happy.txt");
file.seekp(0,file.end);
int fileEndCursor = file.tellp();
file << (char)c; //store what the user typed into file
file.close();
}
}
但是事实证明,文件未清除,每次代码运行完毕,上次运行的内容仍在文件中。请帮忙。
您尝试将其打开两次:
fstream file("happy.txt");
file.open("happy.txt", fstream::out|fstream::in|fstream::trunc );
第一次尝试在构造函数中打开它而没有告诉它截断,因此仅打开它,将所有内容保留在里面。
因为它已经打开,所以第二次调用不会执行任何操作。
通过更改来修复
fstream file("happy.txt");
到
fstream file;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句