設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 748|回復: 0
打印 上一主題 下一主題

11. File Input/Output (Header <fstream>)

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2016-1-1 20:29:26 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
11.  File Input/Output (Header <fstream>)
The <fstream> header provides ifstream (input file stream) and ofstream (output file stream) for file input and output.
The steps for file input/output are:

  • Create a ifstream for input, or ofstream for output.
  • Connect the stream to an input or output file via open(filename).
  • Perform formatted output via stream insertion operator <<, or input via stream extraction operator >>, similar to cout << and cin >>.
  • Close the file and free the stream.
11.1  Example: File IO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* Test File I/O (TestFileIO.cpp)
   Read all the integers from an input file and
   write the average to an output file        */
#include <iostream>
#include <fstream>   // file stream
#include <cstdlib>
using namespace std;

int main() {
   ifstream fin;   // Input stream
   ofstream fout;  // Output stream

    // Try opening the input file
   fin.open("in.txt");
   if (!fin.is_open()) {
      cerr << "error: open input file failed" << endl;
      abort();  // Abnormally terminate the program (in <cstdlib>)
   }

    int sum = 0, number, count = 0;
   while (!(fin.eof())) {
      // Use >> to read
      fin >> number;
      sum += number;
      ++count;
   }
   double average = double(sum) / count;
   cout << "Count = " << count << " average = " << average << endl;
   fin.close();

    // Try opening the output file
   fout.open("out.txt");
   if (!fout.is_open()) {
      cerr << "error: open output file failed" << endl;
      abort();
   }
// Write the average to the output file using <<
   fout << average;
   fout.close();
   return 0;
}
Input File: in.txt
12 15 35 26 68
Output File: out.txt
31.20
Program Notes:

  • Once the file is opened, you can use >> and << for input and output, similar to cin >> and cout <<. (Advanced note: ifstream is a subclass of istream, where cin belongs. ofstream is a subclass of ostream, where cout belongs.)
  • Similarly, IO manipulators, such as fixed, setprecision() and setw(), work on the file streams.
11.2  Exercises
[TODO]


分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-6-13 07:14 , Processed in 0.254740 second(s), 19 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表