c++处理文本文件时,需引用头文件
文件类型分为两种,一种是文本文件,一种是二进制文件
文本文件:文件以文本的ascii码形式存储在计算机中
二进制文件:文件以文本的二进制存储在计算机中
ofstream :写操作
ifstream: 读操作
fstream: 读写操作
#include "base.h"
#include<string>
// 包含 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;
}
/*
// 第一种
char buf[1024];
while (ifs >> buf) { //一行一行读 读到头了返回false
cout << buf << endl;
}
// 第二种
char buf2[1024];
while (ifs.getline(buf2, sizeof(buf2))) {
cout << buf2 << 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 buf;
while (getline(ifs, buf)) {
cout << buf << 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();
/*
// binary 写
ofs.open("pokemon2.txt", ios::out | ios::binary);
ofs.write((const char*)&p1[1], sizeof(p1[1]));
ofs.write((const char*)&p1[0], sizeof(p1[0]));
ofs.close();
// binary 读
ifs.open("pokemon2.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "dont get it" << endl;
}
Pokemon p3;
// Pokemon p4;
ifs.read((char*)&p3, sizeof(p3));
// ifs.read((char*)&p4, sizeof(p4));
cout << p3.name << p3.level << p3.type << endl;
// cout << p4.name << p4.level << p4.type << endl;
ifs.close();
*/
}