C++标准IO库
特性
- 标准库类型不允许做 复制或赋值 操作
- 形参和返回类型 不能是流类型 , 必须使用指针或引用
- 对IO对象的读写会改变状态,因此引用必须是非const的
缓冲区
缓冲区刷新的可能情况
- 程序正常结束
- 缓存区满了
- 用操纵符(manipulator) 显示的刷新缓冲区,e.g. endl
- 使用unitbuf操纵符设置流的内部状态 (C++Primer 红书p250)
- 输出流和输入流 tie 起来
文件的输入和输出
支持文件的IO类型 功能简介 派生源
- ifstream: 读文件; from istream
- ofstream : 写文件; from ostream
- fstream: 对同一个文件读写; from iostream
特殊操作
- open: 打开文件流
- close: 关闭文件流
- clear: 清除文件流的状态
- 形参为要打开文件名的 构造函数
文件模式(file mode)
- 文件模式也是整型常量
- 模式是文件的属性,不是流的属性
- in: 读
- out: 写,同时清空
- app: 文件尾部添加
- ate: 将文件定位在文件尾
- trunc: 清空已存在的文件流
- binary: 二进制模式IO操作
打开检查
//ifstream infile ("1");
ifstream infile;
infile.open("1");
// check up state of opening file
if (! infile )
{ // ok to open file 1
cerr << "open fail: " << "1" << endl;
return -1;
}
二进制读写
- 几个函数
函数 | 用途 |
---|---|
gcount ( ) | 返回最后一次输入所读入的字节数 |
tellg ( ) | 返回输入指针的当前位置 |
seekg ( 文件中的位置 ) | 将输入文件中指针移动到指定的位置 |
seekg ( 位移量, 参照位置 ) | 以参照位置为标准移动指针 |
tellp ( ) | 返回输出文件指针当前位置 |
seekp ( 文件中的位置 ) | 将输出文件中指针移动到指定的位置 |
seekp ( 位移量, 参照位置 ) | 以参照位置为标准移动指针 |
- 系统的参照位置
- ios::beg 所打开文件的开头,这是默认值
- ios::cur 文件读写指针当前的位置
- ios::end 文件结尾
- 实验代码
# include "stdafx.h"
# include <iostream>
# include <fstream>
#include <string>
using namespace std;
int main (int argc ,char **argv)
{
//input param about in-file
string in = argv[1];
//equivalent to:
// ifstream infile ("1");
ifstream infile;
infile.open(in,ifstream::binary);
ofstream outfile("out.txt",ofstream::binary);
// check up state
if (! infile )
{ //wrong to open file(in)
cerr << "open fail" << "in" << endl;
return -1;
}
if (!outfile)
{
// wrong to open file(out)
cerr << "open fail " << "out " << endl;
}
//compute the size of file-in
infile.seekg(0, ios::end);
long fSize = infile.tellg();
//move point to begin
infile.seekg(0, ios::beg);
//set buffer
const int bufferSize = 8;
char p[bufferSize] = {0};
int readLen = bufferSize;
if (fSize < bufferSize)
{
readLen = fSize;
}
while (infile.read(p,readLen))
{
outfile.write(p, readLen);
fSize -= bufferSize;
//output
for (int i =0 ; i != readLen ; ++i)
{
cout << p[i]<<endl;
}
//prefer for next loop
if (fSize < bufferSize)
{
readLen = fSize;
}
if (fSize<0)
{
break;
}
}
// close stream
infile.close();
outfile.close();
cout << "ok" << endl;
system("pause");
return 0;
}