Ofstream: 输出文件流
ASCII 文本文件
- 一个字符一个字符的写
put(char ch);
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
int a[10];
int i;
//指定工作方式ios::out注意这是在定义类对象,文件流ofstream
//ios::out 可以省略
//ofstream outfile("out.dat",ios::out);
ofstream outfile("file/out.dat");
if(outfile==0)
{
cout<<"open error";
exit(1);
}
for(i=0; i<10; i++)
{
cin>>a[i];
outfile<<a[i] << " ";//注意输出流的对数据和字符的两种输出方式
//outfile.put(a[i]);
}
outfile.close();
return 0;
}
- 二进制 字节文件
write(const char *str, int num);
下面的用write方法将字符串写进磁盘文件, 开始我还以为写进去的是文本呢!!
一个字符就使一个字节,所以即使是二进制文件你仍然能看的懂,不要以为写进去的就是文本了。
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
struct Student
{
char name[10];
int age;
double score;
};
int main()
{
Student stu[3] = {
"Larry",19,1000.1,
"Ggeli",20,20000,
"shun", 200, 3000,
};
//注意 这种方式能把文件放入指定的地方
ofstream outfile("file/binary.dat", ios::out | ios::binary);
if(!outfile)
{
cout << "error open" << endl;
exit(1);
}
for(int i=0; i<3; i++)
{
for(int j=0; j<strlen(stu[i].name); j++)
//outfile.put(stu[i].name[j]);
outfile.write(&stu[i].name[j], 1);
}
outfile.close();
return 0;
}
Ifstream: 输入文件流
注意存入文件中的数据是什么类型,最好用什么类型接收
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
int a[10];
int i;
ifstream infile("file/out.dat", ios::in);
if(infile==0)
{
cout<<"open error";
exit(1);
}
for(i=0; i<10; i++)
{
infile>>a[i];
}
// cout << a[1] << endl;
infile.close();
return 0;
}