#include <iostream> #include <fstream> using namespace std; int main() { const char filename[] = "mytext.txt"; ofstream o_file; ifstream i_file; string out_text; //写 o_file.open(filename); for (int i = 1; i <= 10; i++) { o_file << "第" << i << "行"n"; //将内容写入到文本文件中 } o_file.close(); //读 i_file.open(filename); if (i_file.is_open()) { while (i_file.good()) { i_file >> out_text; //将读取的内容存储到变量out_text中 cout << out_text << endl; //在控制台输出读取的内容。为什么最后一行的内容会出现两次 } } else cout << "打开文件:" << filename << " 时出错!"; i_file.close(); system("PAUSE"); return 0; } ############################################################################## #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const char filename[]="test.doc"; ofstream o_file;/* 输出流:将数据从内存输出其中ofstream是将数据输出到文件,因此对于文件来说是“写”*/ ifstream i_file;/*将数据输入到内存,其中ifstream是说输入的数据在文件中,因此对于文件来说是“读”*/ string out_text; //写 o_file.open(filename); for(int i =0;i<=12;i++) { o_file<<"第"<<i<<"行"n";//将内容写入文本 } o_file.close(); //读 i_file.open(filename); if(i_file.is_open()) { while(i_file>>out_text) { cout << out_text << endl; } } else cout<<"打开文件:"<<filename<<"时出错!"; i_file.close(); system("PAUSE"); return 0; }
转自:http://www.cnblogs.com/kiddo/archive/2008/05/27/1208333.html
注意:
在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是: void open(const char* filename,int mode,int access); 参数: filename: 要打开的文件名 mode: 要打开文件的方式 access: 打开文件的属性 打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下: ios::app: 以追加的方式打开文件 ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性 ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文 ios::in: 文件以输入方式打开(文件数据输入到内存) ios::out: 文件以输出方式打开(内存数据输出到文件) ios::nocreate: 不建立文件,所以文件不存在时打开失败 ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败 ios::trunc: 如果文件存在,把文件长度设为0 可以用“或”把以上属性连接起来,如ios::out|ios::binary 打开文件的属性取值是: 0:普通文件,打开访问 1:只读文件 2:隐含文件 4:系统文件 可以用“或”或者“+”把以上属性连接起来,如3或1|2就是以只读和隐含属性打开文件。
