C++实现文件读写,可以使用ifstream、ostream来实现
需要包含头文件
#include
当创建ofstream对象后,可以把ofstream的对象当做cout一样进行输出。
当创建ifstream对象后,可以把ifstream的对象当做cin一样进行输入。
Public member functions
函数 | 功能 |
---|---|
(constructor) | Construct object and optionally open file (public member function ) |
open | Open file (public member function ) |
is_open | Check if a file is open (public member function ) |
close | Close file (public member function ) |
rdbuf | Get stream buffer (public member function ) |
Public member functions inherited from istream
函数 | 功能 |
---|---|
operator>> | Extract formatted input (public member function ) |
gcount | Get character count (public member function ) |
get | Get characters (public member function ) |
getline | Get line (public member function ) |
ignore | Extract and discard characters (public member function ) |
read | Read block of data (public member function ) |
tellg | Get position in input sequence (public member function ) |
seekg | Set position in input sequence (public member function ) |
Public member functions inherited from ios
函数 | 功能 |
---|---|
good | Check whether state of stream is good (public member function ) |
eof | Check whether eofbit is set (public member function ) |
fail | Check whether either failbit or badbit is set (public member function ) |
bad | Check whether badbit is set (public member function ) |
operator bool | Evaluate stream (public member function ) |
rdstate | Get error state flags (public member function ) |
setstate | Set error state flag (public member function ) |
clear | Set error state flags (public member function ) |
Public member functions inherited from ios_base
函数 | 功能 |
---|---|
flags | Get/set format flags (public member function ) |
setf | Set specific format flags (public member function ) |
unsetf | Clear specific format flags (public member function ) |
//默认无参构造
ifstream();
//显式有参构造
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);
//禁止复制构造
ifstream (const ifstream&) = delete;
//移动复制构造
ifstream (ifstream&& x);
关于ios_base::openmode mode的取值,有如下几种:
可取的成员值 | 简述 | 具体含义 |
---|---|---|
in * | input | 打开文件以供读取:内部流缓冲区支持输入操作 |
out | output | 打开供写入的文件:内部流缓冲区支持输出操作 |
binary | binary | 二进制模式 |
ate | at end | 从文件末尾开始输出 |
app | append | 所有输出操作都发生在文件的末尾,即在文件现有内容的尾部去添加。 |
trunc | truncate | 打开之前文件中存在的所有内容都将被丢弃 |
这个标志可以用或运算(|)来组合
//常见的数值类型,注意这里不支持char&类型,表明不能一次读取一个字符
istream& operator>> (bool& val);
istream& operator>> (short& val);
istream& operator>> (unsigned short& val);
istream& operator>> (int& val);
istream& operator>> (unsigned int& val);
istream& operator>> (long& val);
istream& operator>> (unsigned long& val);
istream& operator>> (long long& val);
istream& operator>> (unsigned long long& val);
istream& operator>> (float& val);
istream& operator>> (double& val);
istream& operator>> (long double& val);
//数组
istream& operator>> (void*& val);
//stream buffers (2)
istream& operator>> (streambuf* sb );
//manipulators (3)
istream& operator>> (istream& (*pf)(istream&));
istream& operator>> (ios& (*pf)(ios&));
istream& operator>> (ios_base& (*pf)(ios_base&));
关于operator>>的返回值,
1.返回值为(*this)
2.内部状态错误时,会设置标志位
标志 | 错误 |
---|---|
eofbit | 输入序列中没有更多可用字符(到达文件末尾)。 |
failbit | 没有提取任何字符,或者提取的字符不能解释为适当类型的有效值。 |
badbit | 流上的错误(例如,当此函数捕获内部操作引发的异常时)。 |
-成员函数tellg
streampos tellg();
返回当前字符在流中的位置
istream& seekg (streampos pos);
istream& seekg (streamoff off, ios_base::seekdir way);
参数:
pos
相对于流的开始位置的一个绝对位置,整型
off
相对于参数way指定的起点位置的偏移量,有符号的整型
way
为如下三个值,分别表示流的开始位置,当前位置,结尾位置
way可取的值 | |
---|---|
ios_base::beg | beginning of the stream |
ios_base::cur | current position in the stream |
ios_base::end | end of the stream |
istream& read (char* s, streamsize n);
从流中提取n个字符并将它们存储在s指向的数组中。
此函数仅复制数据块,而不检查其内容或在末尾添加’\0’。
如果在成功读取n个字符之前到达文件末尾(即流中字符数量小于n个),则s指向的数组将包含直到该点之前读取的所有字符,并且eofbit和 为流设置了故障位标志。
示例
// read a file into memory
#include // std::cout
#include // std::ifstream
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
// get length of file:
//1.设置流中下一次提取字符的位置为流的结尾处
is.seekg (0, is.end);
//2.返回当前字符在流中的位置,因为前面将位置设置为了结尾处,
//所以这里返回的就是流中数据的长度
int length = is.tellg();
//3.设置流中下一次提取字符的位置为流的开始处
is.seekg (0, is.beg);
// 申请能容纳流中完整数据的动态数组
char * buffer = new char [length];
//从流中读取数据
is.read (buffer,length);
//关闭文件流
is.close();
//将buffer的数据写入标准输出cout
std::cout.write (buffer,length);
//释放内存
delete[] buffer;
}
return 0;
}
主要是为了能够根据上下文转换为bool类型,使其能够作为判断条件
explicit operator bool() const;
功能:评估stream
返回值:
false:设置了错误标志(failbit或badbit)
true:没有设置错误标志
C++ getline函数用法详解
ifstream的成员函数getline可以用于读取一行字符串,但是需要传入固定大小的字符数组,所以一般不符合我们的需求。
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
这里可以使用std::getline,std::getline相比于ifstream的成员函数getline最大的优势在于不需要预先确定一行字符串的长度,一行字符串,你想输入多长,就输入多长。
http://www.cplusplus.com/reference/string/string/getline/?kw=getline
头文件
<string>
函数声明
//可以看出getline支持string类作为参数
istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);
参数:
is :表示一个输入流
str :string类型的引用,用来存储输入流中的流信息。
delim :char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到’\n’,则终止输入。
// ifstream constructor.
#include // std::cout
#include // std::ifstream
#include //std::getline
int main () {
std::ifstream ifs ("test.txt", std::ifstream::in);
std::string str;
//每次用输入缓冲ifs中读取一行字符串,
//遇到文件结束符时,getline返回fasle,跳出循环
while(std::getline(ifs,str))
std::cout<<str<<std::endl;
ifs.close();
system("pause");
return 0;
}
将文件的内容读入到一个vector< string >中,将每一行作为一个独立的元素存于vector中。
#include
#include
#include
#include
using namespace std;
int main()
{
ifstream ifs("test.txt");
if(!ifs) {
cerr<<"Can't open the file."<<endl;
return -1;
}
string line;
vector<string> result;
while(getline(ifs, line))
result.push_back(line);
ifs.close();
for(auto& i:result)
cout<<i<<endl;
system("pause");
return 0;
}
即将每个单词作为一个独立的元素进行存储
#include
#include
#include
#include
using namespace std;
int main()
{
ifstream ifs("test.txt");
if(!ifs) {
cerr<<"Can't open the file."<<endl;
return -1;
}
string line;
vector<string> result;
while(ifs>>line)
result.push_back(line);
ifs.close();
for(auto& i:result)
cout<<i<<endl;
system("pause");
return 0;
}