zoukankan      html  css  js  c++  java
  • 如何解决读取到文件末尾时碰到EOF导致的重复输出或者无用输出

    当读取到文件末尾时,会碰到EOF,如何解决呢?
        方法一:我们可以通过(ch=fin.get())!=EOF来结束读取,这样就不会像eof()那样碰到EOF之后,还会再进行一次读取,导致输出一个无用的结束符或者重复前一字符

    //a.txt中的内容为abc
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
        ifstream fin("a.txt");
        char ch;
        while((ch=fin.get())!=EOF)                //到达文件结尾即停止读取    
        {
            cout<<ch;
        }
        
        cout<<"eofbit:"<<fin.eof()<<endl;        //文件指针到达文件末尾,因此eofbit被设置为1 
        cout<<"failbit:"<<fin.fail()<<endl;     //同理,failbit被设置为1 
        
        fin.close();
        
        return 0;
    }

    方法二:可以考虑将eof()与fail()结合起来使用来判断文件是否结束

    //a.txt中的内容为abc
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
        ifstream fin("a.txt");
        char ch;
        while(!fin.eof())
        {
            ch=fin.get();                //尝试读取EOF,此时eofbit被置为1,failbit也被置为1 
            if(fin.fail()) break;        //如果碰到EOF,则failbit被设置为1,因此fin.fail()返回true 
            cout<<ch;
        }
        fin.close();
        
        return 0;
    }

    方法三:可以通过get()函数读取EOF则失败来判断文件是否结束

    //a.txt中的内容为abc
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
        ifstream fin("a.txt");
        char ch;
        while(!fin.eof())
        {
            if(fin.get(ch))
                cout<<ch;
        }
        fin.close();
        
        return 0;
    }

    方法四:判断文件指针相对于开头的位置,是否等于文件长度

    //a.txt中的内容为abc
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
        long filelen;
        ifstream fin("a.txt");
        fin.seekg(0, ios::end);
        filelen=fin.tellg();                        //获取文件长度
        fin.seekg(0, ios::beg);
        char ch;
        while(1)
        {
            if(filelen==fin.tellg()) break;            //判断文件指针相对于开头的位置是否等于文件长度
            ch=fin.get();
            cout<<ch;
        }
        fin.close();
        
        return 0;
    }
  • 相关阅读:
    04.openssl-创建 Root CA证书
    03.openssl-获得支持加密算法
    02.openssl-密钥的格式转换
    01.openssl-创建证书签名请求
    00.openssl key generation
    03.openssl中设计中小提示
    会员手机运营商统计
    将属性和方法添加到Date原型中
    AngularJS 指令(意义)
    统计字符串中数字,字母,空格的个数
  • 原文地址:https://www.cnblogs.com/kevinq/p/4492196.html
Copyright © 2011-2022 走看看