C++ 打开文件进行输入和输出
为了使用ofstream对象打开某个文件,先得声明一个ofstream的实例,并把文件名作为参数传给它:
ofstream fout("myfile.cpp");//打开文件myfile.cpp
用户打开一个文件都要进行读或写操作,在此操作之后要关闭文件,这时就用到close(),这一操作保证文件不会被破坏并保证将用户所写的数据保存到磁盘上。
在流对象和文件关联之后,就可以像任何其他流对象一样来使用它。
代码如下:
#include<fstream.h> int main() { char FileName[80]; char buffer[225]; cout<<"File name:"; cin>>FileName; ofstream fout(filename);//打开文件 fout<<"This line write directly to the file---- \n"; cout<<"Enter text for the file:"; cin.ignore(1,'\n'); cin.getline(buffer,255); fout<<buffer<<"\n"; fout.close(); ifstream fin(filename); cout<<"Here is the contents of the file:\n"; char ch; while(fin.get(ch)) cout<<ch; cout<<"\n***the end!***\n"; fin.cose(); return 0; }