c++讀取文字檔的一個極其容易忽略的空行問題

來源:互聯網
上載者:User

標籤:pre   tar   iostream   問題   ase   nts   class   cout   bin   

 C++用fstream開啟檔案之後,讀一次檔案後,再次讀該檔案卻怎樣也不能將檔案的指標置到開頭?2012-12-20 07:41 2859人閱讀 評論(0) 收藏 舉報分類:c++(4) 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
class Copy_file{
    public:
    Copy_file();
    ~Copy_file();
    void Copy_files();
    void in_file();
    void out_file();
    private:
    fstream inf;
    fstream outf;
    char file1[20];
    char file2[20];
};
Copy_file::Copy_file(){
    cout<<"請輸入源檔案名稱";
    cin>>file1;
    inf.open(file1,ios::in|ios::binary);
    if(!inf){
        cout<<"不能開啟檔案"<<endl;
        abort();
    }
    cout<<"請輸入目的檔案名稱字";
    cin>>file2;
    outf.open(file2,ios::in|ios::out|ios::binary);
    if(!outf){
        cout<<"不能開啟目的檔案";
        abort();
    }
}
Copy_file::~Copy_file(){
    inf.close();
    outf.close();
}
void Copy_file::Copy_files(){
    char ch;
    inf.seekg(0);
    inf.get(ch);
    while(!inf.eof()){
        if(ch>=‘a‘ && ch<=‘z‘)
            outf.put(ch);
        inf.get(ch);
    }
}
void Copy_file::in_file(){
    char ch;
   /* inf.close();
    inf.open(file1,ios::in|ios::binary);*/      //  採用關閉檔案後,在開啟檔案可以把指標指到開頭
    inf.clear();   
   cout<<inf.tellg();
   inf.seekg(ios::beg);


   // inf.seekg(5,ios::cur);
    inf.get(ch);
    while(!inf.eof()){
        cout<<ch;
        inf.get(ch);
    }
    cout<<endl;
}
void Copy_file::out_file(){
    char ch;
    outf.seekg(0);
    outf.get(ch);
    while(!outf.eof()){
        cout<<ch;
        outf.get(ch);
    }
    cout<<endl;
}
int main()
{
    Copy_file cf;
    cf.Copy_files();
    cout<<"源檔案內容:"<<endl;
    cf.in_file();
    cout<<"目的檔案的內容:"<<endl;
    cf.out_file();
    return 0;

}

 

這個意思是將ss.txt的內容複寫到oo.txt   cout<<inf.tellg();  輸出當前指標位置時,卻一直返回-1  怎麼都不能用inf.seekg(iOS::beg);將指標指到開頭,這個問題我查了一個早上才發現解決辦法。。。

 


在定位前對流狀態標誌進行清除就可以了:   inf.clear();   inf.seekg(0,ios::beg);file1讀結束後,eof()返回真值時,file1的錯誤標誌被設定為eofbit,於是,後續所有針對file1的操作都不能得到預期的結果,比如tellp、tellg、seekg、seekp等,因此,在進行其他針對file1的操作前,需要清除該錯誤標誌~~~!

 

 

還有一種解決辦法是

    inf.close();
    inf.open(file1,ios::in|ios::binary);  關閉檔案,然後再開啟該檔案

c++讀取文字檔的一個極其容易忽略的空行問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.