ifstream简介: C++平台用来文件操作的库

std::ifstream



常用方法:

open(): ifstream关联文件的方式有两种,通过ifstream构造函数以及通过open来打开一个文件流

example:

ifstream input_file(FILE_NAME);

// OR

ifstream input_file2;
input_file2.open(FILE_NAME, ifstream::in); //ifstream::in 是打开的mode,有多种打开mode,见下文
mode     描述
in *读取文件
out写入模式,适用于output
binary二进制模式
ate起点设置在文件的结尾  at the end of file
app在文件的结尾进行文件的操作,写入.
trunc放弃所有文件之前的内容(很危险!会清空文件内容).



close()   // 关闭一个文件


get_line()

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

获取文件流中的一行数据,保存为一个c字符串形式(char *),结束标志是换行符 \n,n表示能写入s的最大字符数量(包括'\0')

delim参数:当匹配这个指定的字符的时候,结束数据的写入(这种情况不会将failbit位置为true,文件读取成功)

注意:

1. 如果读取的是一个空字串,而n大于0的话,会在s中自动写入一个字串结束标识符 '\0'

2. 如果读取的字符大于n或者等于n,但是这个时候并没有到达这行的结尾,也就是没有到换行符的位置,说明这行数据并不完整,这时候failbit会被置为true


eof()

检查eofbit是true还是false,以此来判断文件是否读取完毕(到文件的EOF位,算是end_of_file)


clear()

清楚错误信息,将goodbit设置为true

iostate value
(member constant)
indicatesfunctions to check state flags
good()eof()fail()bad()rdstate()
goodbitNo errors (zero value iostate)truefalsefalsefalsegoodbit
eofbitEnd-of-File reached on input operationfalsetruefalsefalseeofbit
failbitLogical error on i/o operationfalsefalsetruefalsefailbit
badbitRead/writing error on i/o operationfalsefalsetruetruebadbit


代码示例:

功能:将file1中的每一行单独读取并保存到string容器中

#include<fstream>
#include<string>
#include<vector>
#include<iostream>

#define FILE_NAME "file1"

using namespace std;

int main()

{

        ifstream input_file;

        vector<string> ivec;

        string s;

        input_file.open(FILE_NAME, ifstream::in);

        while(!input_file.eof())

        {

                getline(input_file, s);

                ivec.push_back(s);

                //cout << s.c_str() << endl;

        }

        vector<string>::const_iterator itor = ivec.begin();

        for(itor;itor != ivec.end(); itor ++)

        {

                cout << *itor << endl;

        }

        return 0;

}



Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐