Notes from C++ Primer

File State

Condition state is used to manage stream state, which indicates if the stream is available or recoverable.

State of stream is descripted by three member function: bad, fail, eof and good.

  • bad(): unrecoverable error. If the stream state is badbit, then it can't be used again. bad() returns true.
  • fail(): recoverable error. If the stream state is failbit, fail() returns true.
  • eof(): when stream meets the end-of-file. eofbit will be set. Also, the stream will be set failbit at the same time.
  • good(): the state of stream. If one of bad, fail, eof  is true, the good will return false, otherwise return true.

There're two operations to change the condition state: clear, setstate.

  • clear: reset the stream to be available.
  • setstate: open one of specified condition state.

The mangement of stream can be like this:

int ival;

// read cin and test only for EOF; loop is executed even if there are other IO failures
while(cin >> word, !cin.eof())
{
if(cin.bad()) // input stream is corrupted; bail out
throw runtime_error("IO stream corrupted"); if(cin.fail()) // bad input
{
cerr << "bad data, try again"; // warn the user
cin.clear(istream::failbit); // reset the stream
continue;
} // ok to process ival
...
}

Member function rdstate() returns the current state of stream. The below example also display how to set the state of stream:

// remember current state of cin
istream::iostate old_state = cin.rdstate(); cin.clear();
process_input(); // use cin cin.clear(old_state); // now reset cin to old state ... // sets both the badbit and the failbit
is.setstate(ifstream::badbit | ifstream::failbit);

Use of File Stream

Assume ifle and ofile is the string object storing the names of input and output files' namess.

string ifile = "inputFile.txt";
string ofile = "outputFile.txt";

Then the use of file stream is like this:

// construct an ifstream and bind it to the file named ifile
ifstream infile(ifile.c_str());
// ofstream output file object to write file named ofile
ofstream outfile(ofile.c_str());

Also, we can define unbound input and output file stream first, and then use open function to boud the file we'll access:

ifstream infile;                // unbound input file stream
ofstream outfile; // unbound output file stream infile.open("in"); // open file named "in" in the current directory
outfile.open("out"); // open file named "out" in the current directory

After opening the file, we need to check if it is successful being opened:

// check that the open succeeded
if(!infile){
cerr << "error: unable to open input file: "
<< infile << endl; return -1;
}

Rebound File Stream with New File

If we want to bound the fstream with another file, we need to close the current file first, and then bound with another file:

ifstream infile("in");          // open file named "in" for reading
infile.close(); // closes "in"
infile.open("next"); // open file named "next" for reading

Clear File Stream Status

Opening all file names in a string vector, one direct version is:

vector<string> files;
...
vector<string>::const_iterator it = files.begin();
string s; // string buffer // for each file in the vector
while(it != files.end()){
ifstream input(it->c_str()); // open the file // if the file is ok, read and "process" the input
if(!input)
break; // error: bail out!
while(input >> s) // do the work on this file
process(s);
++it; // increament iterator to get next file
}

More efficient way but with much more accurate operation version:

ifstream input;
vector<string>::const_iterator it = files.begin(); // for each file in the vector
while(it != files.end()){
input.open(it->c_str()); // open the file // if the file is ok, read and "process" the input
if(!input)
break; // error: bail out!
while(input >> s) // do the work on this file
process(s); input.close(); // close file when we're done with it
input.clear(); // reset state to ok
++it;
}

File Mode

When you use ofstream to open file, the only way to store existing data is to set the app mode explicitly.

// output mode by default; truncates file named "file1"
ofstream outfile("file1"); // equivalent effect: "file1" is explicitly truncated
ofstream oufile2("file1", ofstream::out | ofstream::trunc); // append mode: adds new data at end of existing file named "file2"
ofstream appfile("file2", ofstream::app);

File mode is the attribute of file, not stream

ofstream outfile;
// output mode set to out, "scratchpad" truncated because of after definition
outfile.open("scratchpad", ofstream::out);
outfile.close(); // close outfile so we can rebind it // appends to file named "precious"
outfile.open("precious", ofstream::app);
outfile.close(); // output mode set by default, "out" truncated
outfile.open("out");

Input and Output File的更多相关文章

  1. Filebeat之input和output(包含Elasticsearch Output 、Logstash Output、 Redis Output、 File Output和 Console Output)

    前提博客 https://i.cnblogs.com/posts?categoryid=972313 Filebeat啊,根据input来监控数据,根据output来使用数据!!! Filebeat的 ...

  2. Python Tutorial 学习(七)--Input and Output

    7. Input and Output Python里面有多种方式展示程序的输出.或是用便于人阅读的方式打印出来,或是存储到文件中以便将来使用.... 本章将对这些方法予以讨论. 两种将其他类型的值转 ...

  3. [20171128]rman Input or output Memory Buffers.txt

    [20171128]rman Input or output Memory Buffers.txt --//做一个简单测试rman 的Input or output Memory Buffers. 1 ...

  4. Java中的IO流,Input和Output的用法,字节流和字符流的区别

    Java中的IO流:就是内存与设备之间的输入和输出操作就成为IO操作,也就是IO流.内存中的数据持久化到设备上-------->输出(Output).把 硬盘上的数据读取到内存中,这种操作 成为 ...

  5. 标准库 - 输入输出处理(input and output facilities) lua

    标准库 - 输入输出处理(input and output facilities)责任编辑:cynthia作者:来自ITPUB论坛 2008-02-18 文本Tag: Lua [IT168 技术文档] ...

  6. [译]The Python Tutorial#7. Input and Output

    [译]The Python Tutorial#Input and Output Python中有多种展示程序输出的方式:数据可以以人类可读的方式打印出来,也可以输出到文件中以后使用.本章节将会详细讨论 ...

  7. C lang:character input and output (I/O)

    Xx_Introduction Character input and output is by more line character conpose of the text flow  Defin ...

  8. 7. Input and Output

    7. Input and Output There are several ways to present the output of a program; data can be printed i ...

  9. Compiler Error Message: CS0016: Could not write to output file 回绝访问

    Compiler Error Message: CS0016: Could not write to output file 'c:\Windows...dll' 拒绝访问 C:\Windows\Te ...

随机推荐

  1. C#使用GET、POST请求获取结果,这里以一个简单的用户登陆为例。

    1. 使用GET请求获取结果 1.1 创建LoginHandler.aspx处理页面 protected void Page_Load(object sender, EventArgs e) { st ...

  2. 第二篇*2、Python字符串格式化

    1.字符串格式化 Python的字符串格式化有两种方式: 百分号方式.format方式 1)百分号方式 %[(name)][flags][width].[precision]typecode (nam ...

  3. html 提取 公用部分

    在写HTML时,总会遇到一些公用部分,如果每个页面都写那就很麻烦,并且代码量大大增加. 网上查询了几种方法: 1.es6 的 embed 标签. <embed src="header. ...

  4. C# 导出dataGridView中的值到Excel

    C# 怎么导出dataGridView中的值到Excel 1 2 3 4 5 6 在系统应用过程中,数据是系统的核心.如果直接在应用软件中看数据,有时也有些不便,所以就会把系统数据转换成Excel格式 ...

  5. IO高级应用关于字符码表

    ASCII码表: 计算机里只有数字,我在计算机软件里的一切都是用数字来表示,屏幕上显示的一个个字符也不例外.计算机诞生在美国,最开始所用到字符就是我们现在键盘上的一些符号和少数几个特殊的符号,每一个字 ...

  6. as3.0画直线

    import flash.display.Shape; import flash.events.MouseEvent; import flash.geom.Point; var line:Shape; ...

  7. 20175314 《Java程序设计》第五周学习总结

    20175314 <Java程序设计>第五周学习总结 教材学习内容总结 public接口可以被任意一个类实现,友好接口可被同一个包里的接口实现. Java不支持多重继承,即一个类只能有一个 ...

  8. Dubbo helloword

    首先,开始编写服务提供者的api接口, SampleService  接口 package bhz.dubbo.sample.provider; import java.util.List; publ ...

  9. php之$_SESSION的理解

    1.什么是session?       Session的中文译名叫做“会话”,其本来的含义是指有始有终的一系列动作/消息,比如打电话时从拿起电话拨号到挂断电话这中间的一系列过程可以称之为一个sessi ...

  10. Linux驱动之一个简单的输入子系统程序编写

    的在Linux驱动之输入子系统简析已经分析过了输入子系统的构成,它是由设备层.核心层.事件层共同组成的.其中核心层提供一些设备层与事件层公用的函数,比如说注册函数.反注册函数.事件到来的处理函数等等: ...