IO

分类方法/函数头文件用途示例代码适用场景
C++ 流式读写std::ifstream文本/二进制读cpp std::ifstream fin(“a.txt”); fin » x;类型安全的高层读写
std::ofstream文本/二进制写cpp std::ofstream fout(“a.txt”); fout « x;
std::fstream文本/二进制读写cpp std::fstream file(“a.bin”, std::ios::binary|std::ios::in|out);需要随机访问的二进制文件
C 标准库fopen() + fread()/fwrite()<stdio.h>二进制读写c FILE* f = fopen(“a.bin”, “rb”); fread(&x, sizeof(int), 1, f);跨平台二进制操作
fopen() + fscanf()/fprintf()<stdio.h>格式化文本读写c fprintf(f, “%d”, x);结构化文本文件
fgets()/fputs()<stdio.h>行式文本读写c fgets(buf, 100, f);逐行处理文本
POSIX 系统调用open() + read()/write()<fcntl.h>低层二进制读写c int fd = open(“a.bin”, O_RDWR); read(fd, &x, sizeof(x));需要精细控制(如非阻塞IO)
mmap()<sys/mman.h>内存映射文件c void* p = mmap(…, fd, …);大文件随机访问
内存文件fmemopen() (POSIX)<stdio.h>将内存模拟为文件c FILE* memf = fmemopen(buf, size, “r+”);内存数据流处理
std::stringstreamC++ 内存流

有时候涉及到文件流和字符串流综合运用的场景

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <fstream>
#include <sstream>
#include <string>

void parseFileLines(const std::string& filename) {
    std::ifstream fin(filename);
    std::string line;
    while (std::getline(fin, line)) {      // 逐行读取文件
        std::istringstream iss(line);      // 每行转为字符串流
        int x, y;
        iss >> x >> y;                     // 从字符串流解析数据
        std::cout << "Parsed: " << x << ", " << y << "\n";
    }
}
0%