普通文件
首先引入头文件
#inlcude <fstream>
,这个头文件里包含ifstream 和 ofstream。
代码示例:
#inlcude <fstream>
char* fileName = "input.txt";
// 构造函数打开, 只读模式
std::ifstream ism(fileName, std::ios::in);
// or
//成员函数打开
std::ifstream ism;
ism.open(fileName, std::ios::in);
if (!ism){
std::cout << "Open file failed!" << std::endl;
}
// 只读并追加模式打开文件
std::ofstream osm("target.txt", std::ios::out | std::ios::app);
std::string s;
while(ism >> s){
std::cout << s << std::endl;
osm << s << std::endl;
}
ism.close();
osm.close();
二进制文件
如果是二进制文件,需要使用二进制模式,即
ios::binary
。
而
ifstream
拥有
read
成员函数,其原型为:
basic_istream& read (char_type* __s, streamsize __n);
ofstream
拥有
write
成员函数,其原型为:
basic_ostream& write(const char_type* __s, streamsize __n);
代码示例:
//Person 为一个类,相对于将 Person 类序列化存储
Person* p1 = new Person("daming", 14);
Person* p2 = new Person("laoA", 17);
std::ofstream osm = std::ofstream("target", std::ios::out| std::ios::binary);
osm.write((char*)p1, sizeof(Person));
osm.write((char*)p2, sizeof(Person));
osm.close();
std::ifstream ism = std::ifstream("target", std::ios::in | std::ios::binary);
Person p3, p4;
ism.read((char*)&p3, sizeof(Person));
ism.read((char*)&p4, sizeof(Person));
ism.close();
模式一览
除了上文中用到的
ios::in
、
ios::out
、
ios::app
、
ios::binary
模式之外,还有其他一些模式,列在下表
模式 | 含义 |
---|---|
ios::in | 打开文件用于读取 |
ios::out | 打开文件用于写入 |
ios::app | 追加模式,所有写入都追加到文件末尾 |
ios::binary | 二进制方式 |
ios::ate | 文件打开后定位到文件末尾。 |
ios::trunc | 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0 |
文件位置指针
istream 和 ostream 定义了重新定位文件位置指针的成员函数,可以从文件的指定位置开始读取文件。
seekg(“seek get”) 定义在 ifstream 中,seekp(“seek put”)定义在 ofstream 中。它们的参数通常是一个长整型。第二个参数可以用于指定查找方向。查找方向可以是 ios::beg(默认)或是 ios::cur(从流的当前位置开始定位),或是 ios::end。
// 接上文代码示例,可以跳过第一个人,而直接从文件中读取第二个人的信息。
ism.seekg(sizeof(Person));
ism.read((char*)&p4, sizeof(Person));
附录:
Person 类的简单实现:
Person.h
//
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
class Person{
int age;
char* name;
public:
Person(){}
Person(char* name, int age):name(name), age(age){}
void show();
};
#endif /* PERSON_H */
Person.cpp
#include "Person.h"
void Person::show(){
std::cout << name << " " << age << std::endl;
}