c++处理文本文件时,需引用头文件
文件类型分为两种,一种是文本文件,一种是二进制文件
文本文件:文件以文本的ascii码形式存储在计算机中
二进制文件:文件以文本的二进制存储在计算机中
ofstream :写操作
ifstream: 读操作
fstream: 读写操作
#include "base.h" #include// 包含 fstream 头文件 int main() { ofstream ofs; // 写文件 //ofs.open("toto.txt", ios::in); //ofs << "hello worldhello"; //ofs.close(); //读文件 ifstream ifs; ifs.open("toto.txt", ios::in); if (!ifs.is_open()) { cout << "open fail" << endl; } // 第三种 string buf3; while (getline(ifs, buf3)) { cout << buf3 << endl; } ifs.close(); }
二进制文件操作
以二进制的方式对文件进行操作时,打开方式要指定为ios::binary
写文件:
二进制方式写文件主要利用流对象调用成员函数write
函数原型: ostream & write(const char * buf, int len);
字符指针buf指向内存中的一段存储空间,len是读写的字节数
读同理 ostream & read(char * buf,int len);
buf指向内存中一段存储空间,len是读写的字节数
int main() {
Pokemon p1[2];
p1[0].type = "水";
p1[0].level = 50;
p1[0].name = "水箭龟";
p1[1].type = "火";
p1[1].level = 60;
p1[1].name = "喷火龙";
ofstream ofs;
ofs.open("pokemon.txt", ios::out);
for (int i = 0; i < 2; i++) {
ofs << p1[i].name << " " << p1[i].type << " " << p1[i].level << endl;
}
ofs.close();
ifstream ifs;
ifs.open("pokemon.txt", ios::in);
if (!ifs.is_open()) {
cout << "open file" << endl;
}
string name;
string type;
int level;
while (ifs >> name && ifs >> type && ifs >> level) {
Pokemon* poke = NULL;
poke = new Pokemon(name, type, level);
cout << poke->name << poke->type << poke->level << endl;
}
ifs.close();
}



