文件在考研复试中考的很少,大概会用即可
头文件:<fstream>
1.打开文件并写内容
#include <iostream>
#include <fstream>
using namespace std;
#include <fstream>
using namespace std;
int main()
{
ofstream outfile;
outfile.open("red.txt");
outfile<<"test"<<endl;
{
ofstream outfile;
outfile.open("red.txt");
outfile<<"test"<<endl;
outfile<<"test2"<<endl;
outfile.close();
return 0;
}
outfile.close();
return 0;
}
原本没有这个文件,也会被新建出来,内容不管原来是啥,都会改成第一行test,第二行test2
2.读入文件内容
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
ifstream infile;
string instr;
infile.open("red.txt");
if(!infile.is_open()){
cout<<"wrong!"<<endl;
exit(EXIT_FAILURE);//include<cstdlib>
}
infile>>instr;
cout<<instr;
return 0;
}
{
ifstream infile;
string instr;
infile.open("red.txt");
if(!infile.is_open()){
cout<<"wrong!"<<endl;
exit(EXIT_FAILURE);//include<cstdlib>
}
infile>>instr;
cout<<instr;
return 0;
}
这样将把red的第一行空格或者回车前的string输出,换成int char同理