使用IO流进行文件读取

 

对文件操作类包括ofstreamifstreamfstream。其中fstreamiostream(istreamostream派生)的派生类,ofstreamostream派生类,ifstreamistream派生类,从而对文件进行读写操作。

 

1、写文件:当有该文件时打开该文件,没有时自行创建。可使用

 

                        ofstream LogFile("d://test.txt", ios::app);

                       

                        if(!LogFile)//或者写成myfile.fail()

                        {

                                    cout<<"文件读错误!";

                                    system("pause");

                        }

 

                        LogFile << "Log Message Received:" << endl;

                        LogFile << ""tTime_Stamp: " << ACE_TEXT_ALWAYS_CHAR (ACE_OS::ctime                              (&epoch)) << flush;

 

                        第二种调用方式:

                        ofstream LogFile;

                        LogFile.open("d://test.txt", ios::app);

                       

                        LogFile << "Log Message Received:" << endl;

 

2、读文件:单个字符读到ch;整个文件内容读到字符串content;

            #include <iostream>

            #include <fstream>

            #include <string>

            using namespace std;

 

            int main() 

            {

            ifstream myfile;

            myfile.open("d:""1.txt",ios::in);

            if(!myfile)

            {

                        cout<<"文件读错误";

                        exit(1);

            }

            char ch;

            string content;

 

            while(myfile.get(ch))

            {

                        content += ch;

                        cout<<ch<<endl;//cout<<ch;这么写也是可以的

            }

            myfile.close();

            cout<<content<<endl;

            }

posted on 2008-10-10 14:12  王少敏  阅读(270)  评论(0)    收藏  举报

导航