第17章:输入、输出和文件

/* 使用结构来记录知识 - 知识体系 */
本章主要讲解 IO 库的使用。5个点。

  1. IO 类的关系
    a. ios 包含 streambuf ,i/ostream 分别继承 ios ,iostream 多重继承 i/ostream 。

  2. cout
    a. 如何输出: << 重载;.put .write
    b. 如何显示:setf 设置显示格式

  3. cin
    a. 如何输入: >> 重载;.get .getline .peek 等
    b. 输入异常状态:.good

  4. i/ofstream 文件
    a. 初始化: .open ,构造;打开模式; .close
    b. 流状态:.good .eof 等
    c. 定位:.tellp .tellg

  5. ostringstream - snprintf
    a. .str() 转换为 string 对象


附上简单使用代码:

/**
 *  17: I/O
 *      1. 文件-打开、关闭
 *      2. 读取、存入
 *      3. 设置显示格式、检查错误
 *      4. 组装格式化字符串
 */

#include 
#include 
#include 
#include 
#include 

using namespace std;

const char *SRC_FILE = "main.cpp";
const char *CP_FILE = "cp.txt";

int main()
{
    char buf[BUFSIZ];
    ifstream src;
    ofstream dst;
    ostringstream fmt;


    src.open(SRC_FILE);
    if (!src.good())
    {
        cerr << "error." << endl;
        exit(1);
    }

    dst.open(CP_FILE);
    if (!dst.good())
    {
        cerr << "error." << endl;
        exit(1);
    }

    while (src.getline(buf, BUFSIZ))
    {
        cout << buf << endl;
    }
    src.clear();        // 想要重新读写,清除 eof 标志很重要

    cout << "..... Write to " << CP_FILE << "...... " << endl;


    src.seekg(0);

    dst << "/* auto copy from main.cpp */" << endl;
    while (src.getline(buf, BUFSIZ))
    {
        dst << buf << endl;
    }

    fmt << "// buf size is:" << setw(10) << BUFSIZ << "byte." << endl;

    dst << fmt.str() << endl;

    src.close();
    dst.close();

    return 0;
}


我是伍栎,一个用文字记录成长的程序猿。

你可能感兴趣的:(第17章:输入、输出和文件)