C++ I/O流与文件操作速查
目录
输入输出流(I/O Stream)
文件流(File Stream)
一、输入输出流(I/O Stream)
1. 基本概念
输入流:键盘、文件、光笔...
输出流:显示器、文件、打印机...
C++ I/O 系统为用户提供了 统一接口,通过抽象的“流”来屏蔽底层设备差异。
类体系:
ios
(基类)istream
(输入流,如cin
)ostream
(输出流,如cout
)iostream
(输入/输出流)
2. 重载输入/输出运算符
为了让对象能像基本类型一样用 cin >> obj; cout << obj;
操作,可以重载 >>
和 <<
。
输入运算符 >>
friend istream& operator>>(istream&, ClassName&);
输出运算符 <<
friend ostream& operator<<(ostream&, ClassName&);
示例
class InCount {int c1, c2;
public:InCount(int a=0, int b=0): c1(a), c2(b) {}friend istream& operator>>(istream&, InCount&);friend ostream& operator<<(ostream&, InCount&);
};istream& operator>>(istream& is, InCount& cc) {return is >> cc.c1 >> cc.c2;
}ostream& operator<<(ostream& os, InCount& cc) {return os << "c1=" << cc.c1 << "\t" << "c2=" << cc.c2;
}int main() {InCount obj1, obj2;cin >> obj1 >> obj2;cout << obj1 << endl << obj2 << endl;
}
二、文件流(File Stream)
1. 文件流类
ifstream
→ 文件输入流ofstream
→ 文件输出流fstream
→ 文件输入/输出流
头文件:
#include <fstream>
2. 常用方法
方法 | 说明 |
---|---|
open() | 打开文件 |
close() | 关闭文件 |
is_open() | 判断文件是否打开 |
write() | 写入二进制数据 |
read() | 读取二进制数据 |
put() | 写单个字符 |
get() | 读单个字符 |
seekg()/seekp() | 移动文件指针(g=读,p=写) |
tellg()/tellp() | 获取文件指针位置 |
3. 文件打开模式
模式 | 含义 |
---|---|
ios::in | 读文件 |
ios::out | 写文件(清空原内容) |
ios::app | 追加写 |
ios::trunc | 打开时清空文件 |
ios::binary | 二进制方式 |
ios::ate | 打开文件后指针在末尾 |
4. 示例代码
(1)文本写入
fstream fs;
fs.open("demo.txt", ios::out);
fs << "hello world" << endl;
fs.close();
(2)二进制写入/读取
class student {
public:int no;char name[10];int age;
};// 写文件
ofstream outFile("student.dat", ios::binary);
student stu = {1, "Tom", 20};
outFile.write((char*)&stu, sizeof(stu));
outFile.close();// 读文件
ifstream inFile("student.dat", ios::binary);
student s;
while (inFile.read((char*)&s, sizeof(s))) {cout << s.no << "," << s.name << "," << s.age << endl;
}
inFile.close();
(3)put()/get() 单字符操作
ofstream out("outdemo.txt", ios::binary);
out.put('A');
out.close();ifstream in("outdemo.txt", ios::binary);
char ch;
while ((ch = in.get()) != EOF) {cout << ch;
}
in.close();
三、文件指针操作
infile.seekg(100, ios::beg); // 从文件头偏移100字节
infile.seekg(-50, ios::cur); // 从当前位置向前50字节
infile.seekg(-100, ios::end); // 从文件尾向前100字节
四、总结
I/O 流是 C++ 对输入输出设备的统一抽象。
重载
>>
和<<
可让类对象支持类似基本类型的输入输出。文件流常用
ifstream
、ofstream
、fstream
。文本文件和二进制文件的读写方法不同,二进制更高效。
熟悉
open/close
、read/write
、put/get
、seekg/seekp
等常用方法。