| 示例代码如下:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <fstream> using namespace std; int main() { ofstream myfile("c:\\1.txt",ios::out|ios::trunc,0); myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com"; myfile.close() system("pause"); }
文件使用完后可以使用close成员函数关闭文件。
ios::app为追加模式,在使用追加模式的时候同时进行文件状态的判断是一个比较好的习惯。
示例如下:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> #include <fstream> using namespace std; int main() { ofstream myfile("c:\\1.txt",ios::app,0); if(!myfile)//或者写成myfile.fail() { cout<<"文件打开失败,目标文件状态可能为只读!"; system("pause"); exit(1); } myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com"<<endl; myfile.close(); }
在定义ifstream和ofstream类对象的时候,我们也可以不指定文件。以后可以通过成员函数open()显式的把一个文件连接到一个类对象上。
例如:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> #include <fstream> using namespace std; int main() { ofstream myfile; myfile.open("c:\\1.txt",ios::out|ios::app,0); if(!myfile)//或者写成myfile.fail() { cout<<"文件创建失败,磁盘不可写或者文件为只读!"; system("pause"); exit(1); } myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com"<<endl; myfile.close(); }
下面我们来看一下是如何利用ifstream类对象,将文件中的数据读取出来,然后再输出到标准设备中的例子。
代码如下:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile; myfile.open("c:\\1.txt",ios::in,0); if(!myfile) { cout<<"文件读错误"; system("pause"); exit(1); } char ch; string content; while(myfile.get(ch)) { content+=ch; cout.put(ch);//cout<<ch;这么写也是可以的 } myfile.close(); cout<<content; system("pause"); }
上例中,我们利用成员函数get(),逐一的读取文件中的有效字符,再利用put()成员函数,将文件中的数据通过循环逐一输出到标准设备(屏幕)上,get()成员函数会在文件读到默尾的时候返回假值,所以我们可以利用它的这个特性作为while循环的终止条件,我们同时也在上例中引入了C++风格的字符串类型string,在循环读取的时候逐一保存到content中,要使用string类型,必须包含string.h的头文件。 |