C++ 标准函数库 C++ Standard Library 文件的输入输出 (Input/Output with files) C++ 通过以下几个类支持文件的输入输出: ofstream: 写操作(输出)的文件类 (由ostr6.0 C++ 标准函数库
C++ Standard Library
文件的输入输出 (Input/Output with files)
C++ 通过以下几个类支持文件的输入输出:
ofstream: 写操作(输出)的文件类 (由ostream引申而来)
ifstream: 读操作(输入)的文件类(由istream引申而来)
fstream: 可同时读写操作的文件类 (由iostream引申而来)
打开文件(Open a file)
对这些类的一个对象所做的第一个操作通常就是将它和一个真正的文件联系起来,也就是说打开一个文件。被打开的文件在程序中由一个流对象(stream object)来表示 (这些类的一个实例) ,而对这个流对象所做的任何输入输出操作实际就是对该文件所做的操作。
要通过一个流对象打开一个文件,我们使用它的成员函数open():
void open (const char * filename, openmode mode);
这里filename 是一个字符串,代表要打开的文件名,mode 是以下标志符的一个组合:
ios::in 为输入(读)而打开文件
ios::out 为输出(写)而打开文件
ios::ate 初始位置:文件尾
ios::app 所有输出附加在文件末尾
ios::trunc 如果文件已存在则先删除该文件
ios::binary 二进制方式
这些标识符可以被组合使用,中间以”或”操作符(|)间隔。例如,如果我们想要以二进制方式打开文件"example.bin" 来写入一些数据,我们可以通过以下方式调用成员函数open()来实现:
ofstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
ofstream, ifstream 和 fstream所有这些类的成员函数open 都包含了一个默认打开文件的方式,这三个类的默认方式各不相同:
类 参数的默认方式
ofstream ios::out | ios::trunc
ifstream ios::in
fstream ios::in | ios::out
只有当函数被调用时没有声明方式参数的情况下,默认值才会被采用。如果函数被调用时声明了任何参数,默认值将被完全改写,而不会与调用参数组合。
由于对类ofstream, ifstream 和 fstream 的对象所进行的第一个操作通常都是打开文件,这些类都有一个构造函数可以直接调用open 函数,并拥有同样的参数。这样,我们就可以通过以下方式进行与上面同样的定义对象和打开文件的操作:
ofstream file ("example.bin", ios::out | ios::app | ios::binary);
两种打开文件的方式都是正确的。
你可以通过调用成员函数is_open()来检查一个文件是否已经被顺利的打开了:
bool is_open();
它返回一个布尔(bool)值,为真(true)代表文件已经被顺利打开,假( false )则相反。
关闭文件(Closing a file)
当文件读写操作完成之后,我们必须将文件关闭以使文件重新变为可访问的。关闭文件需要调用成员函数close(),它负责将缓存中的数据排放出来并关闭文件。它的格式很简单:
void close ();
这个函数一旦被调用,原先的流对象(stream object)就可以被用来打开其它的文件了,这个文件也就可以重新被其它的进程(process)所有访问了。
为防止流对象被销毁时还联系着打开的文件,析构函数(destructor)将会自动调用关闭函数close。
文本文件(Text mode files)
类ofstream, ifstream 和fstream 是分别从ostream, istream 和iostream 中引申而来的。这就是为什么 fstream 的对象可以使用其父类的成员来访问数据。
一般来说,我们将使用这些类与同控制台(console)交互同样的成员函数(cin 和 cout)来进行输入输出。如下面的例题所示,我们使用重载的插入操作符<<:
// writing on a text file
#include <fiostream.h>
int main () {
ofstream examplefile ("example.txt");
if (examplefile.is_open()) {
examplefile << "This is a line.\n";
examplefile << "This is another line.\n";
examplefile.close();
}
return 0;
}
file example.txt
This is a line.
This is another line.
从文件中读入数据也可以用与 cin的使用同样的方法:
// reading a text file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main () {
char buffer[256];
ifstream examplefile ("example.txt");
if (! examplefile.is_open())
{ cout << "Error opening file"; exit (1); }
while (! examplefile.eof() ) {
examplefile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
This is a line.
This is another line.
上面的例子读入一个文本文件的内容,然后将它打印到屏幕上。注意我们使用了一个新的成员函数叫做eof ,它是ifstream 从类 ios 中继承过来的,当到达文件末尾时返回true 。
状态标志符的验证(Verification of state flags)
除了eof()以外,还有一些验证流的状态的成员函数(所有都返回bool型返回值):
bad()
如果在读写过程中出错,返回 true 。例如:当我们要对一个不是打开为写状态的文件进行写入时,或者我们要写入的设备没有剩余空间的时候。
fail()
除了与bad() 同样的情况下会返回 true 以外,加上格式错误时也返回true ,例如当想要读入一个整数,而获得了一个字母的时候。
eof()
如果读文件到达文件末尾,返回true。
good()
这是最通用的:如果调用以上任何一个函数返回true 的话,此函数返回 false 。
要想重置以上成员函数所检查的状态标志,你可以使用成员函数clear(),没有参数。
获得和设置流指针(get and put stream pointers)
所有输入/输出流对象(i/o streams objects)都有至少一个流指针:
ifstream, 类似istream, 有一个被称为get pointer的指针,指向下一个将被读取的元素。
ofstream, 类似 ostream, 有一个指针 put pointer ,指向写入下一个元素的位置。
fstream, 类似 iostream, 同时继承了get 和 put
我们可以通过使用以下成员函数来读出或配置这些指向流中读写位置的流指针:
tellg() 和 tellp()
这两个成员函数不用传入参数,返回pos_type 类型的值(根据ANSI-C++ 标准) ,就是一个整数,代表当前get 流指针的位置 (用tellg) 或 put 流指针的位置(用tellp).
seekg() 和seekp()
这对函数分别用来改变流指针get 和put的位置。两个函数都被重载为两种不同的原型:
seekg ( pos_type position );
seekp ( pos_type position );
使用这个原型,流指针被改变为指向从文件开始计算的一个绝对位置。要求传入的参数类型与函数 tellg 和tellp 的返回值类型相同。
seekg ( off_type offset, seekdir direction );
seekp ( off_type offset, seekdir direction );
使用这个原型可以指定由参数direction决定的一个具体的指针开始计算的一个位移(offset)。它可以是:
ios::beg 从流开始位置计算的位移
ios::cur 从流指针当前位置开始计算的位移
ios::end 从流末尾处开始计算的位移
流指针 get 和 put 的值对文本文件(text file)和二进制文件(binary file)的计算方法都是不同的,因为文本模式的文件中某些特殊字符可能被修改。由于这个原因,建议对以文本文件模式打开的文件总是使用seekg 和 seekp的第一种原型,而且不要对tellg 或 tellp 的返回值进行修改。对二进制文件,你可以任意使用这些函数,应该不会有任何意外的行为产生。
以下例子使用这些函数来获得一个二进制文件的大小:
// obtaining file size
#include <iostream.h>
#include <fstream.h>
const char * filename = "example.txt";
int main () {
long l,m;
ifstream file (filename, ios::in|ios::binary);
l = file.tellg();
file.seekg (0, ios::end);
m = file.tellg();
file.close();
cout << "size of " << filename;
cout << " is " << (m-l) << " bytes.\n";
return 0;
}
size of example.txt is 40 bytes.
二进制文件(Binary files)
在二进制文件中,使用<< 和>>,以及函数(如getline)来操作符输入和输出数据,没有什么实际意义,虽然它们是符合语法的。
文件流包括两个为顺序读写数据特殊设计的成员函数:write 和 read。第一个函数 (write) 是ostream 的一个成员函数,都是被ofstream所继承。而read 是istream 的一个成员函数,被ifstream 所继承。类 fstream 的对象同时拥有这两个函数。它们的原型是:
write ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );
这里 buffer 是一块内存的地址,用来存储或读出数据。参数size 是一个整数值,表示要从缓存(buffer)中读出或写入的字符数。
// reading binary file
#include <iostream>
#include <fstream.h>
const char * filename = "example.txt";
int main () {
char * buffer;
long size;
ifstream file (filename, ios::in|ios::binary|ios::ate);
size = file.tellg();
file.seekg (0, ios::beg);
buffer = new char [size];
file.read (buffer, size);
file.close();
cout << "the complete file is in a buffer";
delete[] buffer;
return 0;
}
The complete file is in a buffer
缓存和同步(Buffers and Synchronization)
当我们对文件流进行操作的时候,它们与一个streambuf 类型的缓存(buffer)联系在一起。这个缓存(buffer)实际是一块内存空间,作为流(stream)和物理文件的媒介。例如,对于一个输出流,每次成员函数put (写一个单个字符)被调用,这个字符不是直接被写入该输出流所对应的物理文件中的,而是首先被插入到该流的缓存(buffer)中。
当缓存被排放出来(flush)时,它里面的所有数据或者被写入物理媒质中(如果是一个输出流的话),或者简单的被抹掉(如果是一个输入流的话)。这个过程称为同步(synchronization),它会在以下任一情况下发生:
当文件被关闭时: 在文件被关闭之前,所有还没有被完全写出或读取的缓存都将被同步。
当缓存buffer 满时:缓存Buffers 有一定的空间限制。当缓存满时,它会被自动同步。
控制符明确指明:当遇到流中某些特定的控制符时,同步会发生。这些控制符包括:flush 和endl。
明确调用函数sync(): 调用成员函数sync() (无参数)可以引发立即同步。这个函数返回一个int 值,等于-1 表示流没有联系的缓存或操作失败。
Standard C 语言标准函数库速查 (Cheat Sheet)
http://ganquan.info/standard-c/
英文 |
参考译文
|
---|---|
Ambiguous operators need parentheses
|
不明确的运算需要用括号括起
|
Ambiguous symbol ''xxx''
|
不明确的符号
|
Argument list syntax error
|
参数表语法错误
|
Array bounds missing
|
丢失数组界限符
|
Array size toolarge
|
数组尺寸太大
|
Bad character in paramenters
|
参数中有不适当的字符
|
Bad file name format in include directive
|
包含命令中文件名格式不正确
|
Bad ifdef directive synatax
|
编译预处理ifdef有语法错
|
Bad undef directive syntax
|
编译预处理undef有语法错
|
Bit field too large
|
位字段太长
|
Call of non-function
|
调用未定义的函数
|
Call to function with no prototype
|
调用函数时没有函数的说明
|
Cannot modify a const object
|
不允许修改常量对象
|
Case outside of switch
|
漏掉了case 语句
|
Case syntax error
|
Case 语法错误
|
Code has no effect
|
代码不可述不可能执行到
|
Compound statement missing{
|
分程序漏掉"{"
|
Conflicting type modifiers
|
不明确的类型说明符
|
Constant expression required
|
要求常量表达式
|
Constant out of range in comparison
|
在比较中常量超出范围
|
Conversion may lose significant digits
|
转换时会丢失意义的数字
|
Conversion of near pointer not allowed
|
不允许转换近指针
|
Could not find file ''xxx''
|
找不到XXX文件
|
Declaration missing ;
|
说明缺少";"
|
Declaration syntax error
|
说明中出现语法错误
|
Default outside of switch
|
Default 出现在switch语句之外
|
Define directive needs an identifier
|
定义编译预处理需要标识符
|
Division by zero
|
用零作除数
|
Do statement must have while
|
Do-while语句中缺少while部分
|
Enum syntax error
|
枚举类型语法错误
|
Enumeration constant syntax error
|
枚举常数语法错误
|
Error directive :xxx
|
错误的编译预处理命令
|
Error writing output file
|
写输出文件错误
|
Expression syntax error
|
表达式语法错误
|
Extra parameter in call
|
调用时出现多余错误
|
File name too long
|
文件名太长
|
Function call missing
|
函数调用缺少右括号
|
Fuction definition out of place
|
函数定义位置错误
|
Fuction should return a value
|
函数必需返回一个值
|
Goto statement missing label
|
Goto语句没有标号
|
Hexadecimal or octal constant too large
|
16进制或8进制常数太大
|
Illegal character ''x''
|
非法字符x
|
Illegal initialization
|
非法的初始化
|
Illegal octal digit
|
非法的8进制数字
|
Illegal pointer subtraction
|
非法的指针相减
|
Illegal structure operation
|
非法的结构体操作
|
Illegal use of floating point
|
非法的浮点运算
|
Illegal use of pointer
|
指针使用非法
|
Improper use of a typedefsymbol
|
类型定义符号使用不恰当
|
In-line assembly not allowed
|
不允许使用行间汇编
|
Incompatible storage class
|
存储类别不相容
|
Incompatible type conversion
|
不相容的类型转换
|
Incorrect number format
|
错误的数据格式
|
Incorrect use of default
|
Default使用不当
|
Invalid indirection
|
无效的间接运算
|
Invalid pointer addition
|
指针相加无效
|
Irreducible expression tree
|
无法执行的表达式运算
|
Lvalue required
|
需要逻辑值0或非0值
|
Macro argument syntax error
|
宏参数语法错误
|
Macro expansion too long
|
宏的扩展以后太长
|
Mismatched number of parameters in definition
|
定义中参数个数不匹配
|
Misplaced break
|
此处不应出现break语句
|
Misplaced continue
|
此处不应出现continue语句
|
Misplaced decimal point
|
此处不应出现小数点
|
Misplaced elif directive
|
不应编译预处理elif
|
Misplaced else
|
此处不应出现else
|
Misplaced else directive
|
此处不应出现编译预处理else
|
Misplaced endif directive
|
此处不应出现编译预处理endif
|
Must be addressable
|
必须是可以编址的
|
Must take address of memory location
|
必须存储定位的地址
|
No declaration for function ''xxx''
|
没有函数xxx的说明
|
No stack
|
缺少堆栈
|
No type information/没有类型信息
|
缺少堆栈
|
Non-portable pointer assignment
|
不可移动的指针(地址常数)赋值
|
Non-portable pointer comparison
|
不可移动的指针(地址常数)比较
|
Non-portable pointer conversion
|
不可移动的指针(地址常数)转换
|
Not a valid expression format type
|
不合法的表达式格式
|
Not an allowed type
|
不允许使用的类型
|
Numeric constant too large
|
数值
常太大
|
Out of memory
|
内存不够用
|
Parameter ''xxx'' is never used
|
能数xxx没有用到
|
Pointer required on left side of ->
|
符号->的左边必须是指针
|
Possible use of ''xxx'' before definition
|
在定义之前就使用了xxx(警告)
|
Possibly incorrect assignment
|
赋值可能不正确
|
Redeclaration of ''xxx''
|
重复定义了xxx
|
Redefinition of ''xxx'' is not identical
|
xxx的两次定义不一致
|
Register allocation failure
|
寄存器定址失败
|
Repeat count needs an lvalue
|
重复计数需要逻辑值
|
Size of structure or array not known
|
结构体或数给大小不确定
|
Statement missing ;
|
语句后缺少";"
|
Structure or union syntax error
|
结构体或联合体语法错误
|
Structure size too large
|
结构体尺寸太大
|
Sub scripting missing ]
|
下标缺少右方括号
|
Superfluous & with function or array
|
函数或数组中有多余的"&"
|
Suspicious pointer conversion
|
可疑的指针转换
|
Symbol limit exceeded
|
符号超限
|
Too few parameters in call
|
函数调用时的实参少于函数的参数不
|
Too many default cases
|
Default太多(switch语句中一个)
|
Too many error or warning messages
|
英文
|
参考译文
|
---|---|
Too many type in declaration
|
说明中类型太多
|
Too much auto memory in function
|
函数用到的局部存储太多
|
Too much global data defined in file
|
文件中全局数据太多
|
Two consecutive dots
|
两个连续的句点
|
Type mismatch in parameter xxx
|
参数xxx类型不匹配
|
Type mismatch in redeclaration of ''xxx''
|
xxx重定义的类型不匹配
|
Unable to create output file ''xxx''
|
无法建立输出文件xxx
|
Unable to open include file ''xxx''
|
无法打开被包含的文件xxx
|
Unable to open input file ''xxx''
|
无法打开输入文件xxx
|
Undefined label ''xxx''
|
没有定义的标号xxx
|
Undefined structure ''xxx''
|
没有定义的结构xxx
|
Undefined symbol ''xxx''
|
没有定义的符号xxx
|
Unexpected end of file in comment started on line xxx
|
从xxx行开始的注解尚未结束文件不能结束
|
Unexpected end of file in conditional started on line xxx
|
从xxx 开始的条件语句 尚未结束文件不能结束
|
Unknown assemble instruction
|
未知的汇编结构
|
Unknown option
|
未知的操作
|
Unknown preprocessor directive: ''xxx''
|
不认识的预处理命令xxx
|
Unreachable code
|
无路可达的代码
|
Unterminated string or character constant
|
字符串缺少引号
|
User break
|
用户强行中断了程序
|
Void functions may not return a value
|
Void类型的函数不应有返回值
|
Wrong number of arguments
|
调用函数的参数数目错
|
''xxx'' not an argument
|
xxx不是参数
|
''xxx'' not part of structure
|
xxx不是结构体的一部分
|
xxx statement missing (
|
xxx语句缺少左括号
|
xxx statement missing )
|
xxx语句缺少右括号
|
xxx statement missing ;
|
xxx缺少分号
|
xxx'' declared but never used
|
说明了xxx但没有使用
|
xxx'' is assigned a value which is never used
|
给xxx赋了值但未用过
|
Zero length structure
|