1. 程式人生 > >讀取檔案內容fstream.eof()和peek()

讀取檔案內容fstream.eof()和peek()

a.txt

你好
hello
上午好
中午好
下午好
晚上好
再見

peek.cpp

#include <iostream>
#include <cstdio>
#include <fstream>
#include <string.h>
#include <vector>

using namespace std;



int main()
{

    vector<string> vec;
    char buff[256];
    fstream file;
    file.open("a.txt",ios::binary| ios::in);
    if(file.is_open())
    {
        //while(!file.eof())
        while(file.peek()!=EOF)
        {
            file.getline(buff,sizeof(buff));
            int len = strlen(buff);
            string str = buff;
            cout << "buff = "<< buff<< endl;
            vec.push_back(str);
        }
        int a = vec.size();
        cout << "vec.size=" << a << endl;

    }
    else
    {
        cout << "open failed" << endl;
        return 0;
    }

}

peek.cpp輸出

buff = 你好
buff = hello
buff = 上午好
buff = 中午好
buff = 下午好
buff = 晚上好
buff = 再見
vec.size=7

如果是用

while(!file.eof())

則輸入如下:

buff = 你好
buff = hello
buff = 上午好
buff = 中午好
buff = 下午好
buff = 晚上好
buff = 再見
buff = 
vec.size=8