文本文件读取与写入
#include"bits/stdc++.h"
//文本文件读取与写入
using namespace std;
int main(){
vector<int> v;
ifstream r("in.txt",ios::in);//读取文件
ofstream w("out.txt",ios::out);//写入文件
int x;
while (r>>x)
{
v.push_back(x);//读取x到v;
}
sort(v.begin(),v.end());//排序
for(int i=0;i<v.size();i++){
w<<v[i]<<" ";
}
r.close();
w.close();
return 0;
}
二进制文件读取与写入
#include"bits/stdc++.h"
//二进制文件读取与写入
using namespace std;
int main(){
ofstream xout("wenj.txt",ios::out|ios::binary);
int x=120;
xout.write((const char *)(&x),sizeof(int));
xout.close();
ifstream xin("wenj.txt",ios::in|ios::binary);
int y;
xin.read((char *)(&y),sizeof(int));
xin.close();
cout<<y<<endl;
return 0;
}
二进制文件读取与写入学生信息
#include"bits/stdc++.h"
using namespace std;
//二进制文件写入学生信息
struct student
{
char name[20];
int score;
};
int main(){
student s;
ofstream yout("xueshen.txt",ios::out|ios::binary);
while(cin>>s.name>>s.score)
yout.write((const char*)&s,sizeof(s));
yout.close();
return 0;
}
#include"bits/stdc++.h"
using namespace std;
//二进制文件读取学生信息
struct student
{
char name[20];
int score;
};
int main(){
student s;
ifstream yin("xueshen.txt",ios::in|ios::binary);
if(!yin){
cout<<"erorr"<<endl;
return 0;
}
while (yin.read((char*)&s,sizeof(s)))
{
int readbits=yin.gcount();//返回读取的字节数
cout<<s.name<<" "<<s.score<<" "<<readbits<<endl;
}
yin.close();
return 0;
}