fstream 存取文件以及get()和getline()的区别
取自C++编程思想的源码
require.h 一些小的内联函数
1: #ifndef REQUIRE_H
2: #define REQUIRE_H
3: #include <cstdio>
4: #include <cstdlib>
5: #include <fstream>
6:
7: inline void require(bool requirement,
8: const char* msg = "Requirement failed") {
9: using namespace std;
10: if (!requirement) {
11: fputs(msg, stderr);
12: fputs("\n", stderr);
13: exit(1);
14: }
15: }
16:
17: inline void requireArgs(int argc, int args,
18: const char* msg = "Must use %d arguments") {
19: using namespace std;
20: if (argc != args + 1) {
21: fprintf(stderr, msg, args);
22: fputs("\n", stderr);
23: exit(1);
24: }
25: }
26:
27: inline void requireMinArgs(int argc, int minArgs,
28: const char* msg =
29: "Must use at least %d arguments") {
30: using namespace std;
31: if(argc < minArgs + 1) {
32: fprintf(stderr, msg, minArgs);
33: fputs("\n", stderr);
34: exit(1);
35: }
36: }
37:
38: inline void assure(std::ifstream& in,
39: const char* filename = "") {
40: using namespace std;
41: if(!in) {
42: fprintf(stderr,
43: "Could not open file %s\n", filename);
44: exit(1);
45: }
46: }
47:
48: inline void assure(std::ofstream& in,
49: const char* filename = "") {
50: using namespace std;
51: if(!in) {
52: fprintf(stderr,
53: "Could not open file %s\n", filename);
54: exit(1);
55: }
56: }
每次创建ifstream和ofstream都会有assure()函数来确保文件成功打开。
get()或者读取sz-1个字符或者遇到文件为’\n’然后在buf尾部加0终结符。get()会把文件内遇到终结符留在输入流中,所以需要使用get()将终结符扔掉。也可以使用ignore()函数来做这个事情,第一个参数是要扔掉的字符数,默认为1,第二个参数是要扔掉的字符,默认是EOF。
getline()函数自动把输入流中的’\n’取消掉了。所以下次可以直接读取输入流中的数据,一般使用geiline().
get和getline都在读取后在buf的尾部加了一个字符串结尾终结符‘0’。
1: #include "../require.h"
2: #include <fstream>
3: #include <iostream>
4: using namespace std;
5:
6: int main() {
7: const int sz = 100; // Buffer size;
8: char buf[sz];
9: {
10: ifstream in("Strfile.cpp"); // Read
11: assure(in, "Strfile.cpp"); // Verify open
12: ofstream out("Strfile.out"); // Write
13: assure(out, "Strfile.out");
14: int i = 1; // Line counter
15:
16: // A less-convenient approach for line input:
17: while(in.get(buf, sz)) { // Leaves \n in input
18: in.get(); // Throw away next character (\n)
19: cout << buf << endl; // Must add \n
20: // File output just like standard I/O:
21: out << i++ << ": " << buf << endl;
22: }
23: } // Destructors close in & out
24:
25: ifstream in("Strfile.out");
26: assure(in, "Strfile.out");
27: // More convenient line input:
28: while(in.getline(buf, sz)) { // Removes \n
29: char* cp = buf;
30: while(*cp != ':')
31: cp++;
32: cp += 2; // Past ": "
33: cout << cp << endl; // Must still add \n
34: }
35: } ///:~