C++编程思想 第2卷 第4章 输入输出流 文件输入输出流 一个文件处理的例子
<fstream>的包含声明了文件输入输出类
尽管在许多平台上,声明自动包含<iostream>,但编译器不一定都这样做
//: C04:Strfile.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Stream I/O with files;
// The difference between get() & getline().
#include <fstream>
#include <iostream>
#include "../require.h"
using namespace std;
int main() {
const int SZ = 100; // Buffer size;
char buf[SZ];
{
ifstream in("Strfile.cpp"); // Read
assure(in, "Strfile.cpp"); // Verify open
ofstream out("Strfile.out"); // Write
assure(out, "Strfile.out");
int i = 1; // Line counter
// A less-convenient approach for line input:
while(in.get(buf, SZ)) { // Leaves \n in input
in.get(); // Throw away next character (\n)
cout << buf << endl; // Must add \n
// File output just like standard I/O:
out << i++ << ": " << buf << endl;
}
} // Destructors close in & out
ifstream in("Strfile.out");
assure(in, "Strfile.out");
// More convenient line input:
while(in.getline(buf, SZ)) { // Removes \n
char* cp = buf;
while(*cp != ':')
++cp;
cp += 2; // Past ": "
cout << cp << endl; // Must still add \n
}
getchar();
} ///:~
输出 在工程目录下饭Strfile.cpp
//: C04:Strfile.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Stream I/O with files;
// The difference between get() & getline().
#include <fstream>
#include <iostream>
#include "../require.h"
using namespace std;
//: C04:Strfile.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Stream I/O with files;
// The difference between get() & getline().
#include <fstream>
#include <iostream>
#include "../require.h"
using namespace std;
创建ifstream对象和ofstream对象后都调用了函数assuer(),确保文件被成功打开
第一个while循环演示了两个get()函数的使用
一个输出cout,一个输出到文件out
第2个while循环语句 说明函数getline()遇到输入流中的结束之后 \n如何除去
上一篇: c++文件输入输出
下一篇: C++简单文件输入输出