C++文件读

#include <iostream>
#include <fstream>

int main()
{
   using namespace std;

   ifstream ifs;
   ifs.open("test.txt", ios::in);
   if(!ifs.is_open())
   {
      cout << "open failed" << endl;
      return -1;
   }

   char buf[128];
   while(ifs >> buf)
   {
      cout << buf << endl;
   }

   ifs.clear();
   ifs.seekg(0, ios::beg);
   while(ifs.getline(buf, sizeof(buf)))
   {
      cout << buf << endl;
   }

   ifs.clear();
   ifs.seekg(0, ios::beg);
   string str;
   while(getline(ifs, str))
   {
      cout << str << endl;
   }

   ifs.clear();
   ifs.seekg(0, ios::beg);
   char c;
   while((c = ifs.get()) != EOF)
   {
      cout << c;
   }
   cout << endl;

   ifs.close();

   return 0;
}
$ ./a.out          
hello
furong
i
love
y
hello furong
i love y
hello furong
i love y
hello furong
i love y
posted @ 2022-07-12 16:58  thomas_blog  阅读(26)  评论(0)    收藏  举报