2016-09-30 29 views
0

如何在C++文件中讀取信號時發出EOF信號?我正在編寫一個直接編碼的掃描器,作爲編譯器設計的一部分,它讀入一個文件並將其分割成一個語言的標記。如何在程序打開的文件上發出EOF信號

我要在整個程序中讀取,刪除註釋並壓縮空白。然後把由char生成的程序char放入最大尺寸爲1024個字符的緩衝區中。所以當我們空着的時候,我們會補充緩衝區或者什麼不是。

要打開我有這個寫入的文件:

// Open source file. 
source_file.open (filename); 
if (source_file.fail()) { 
    // Failed to open source file. 
    cerr << "Can't open source file " << *filename << endl; 
    buffer_fatal_error(); 

填充緩衝區,我想用while循環和重複像

int i = 0; 
// Iterate through the whole file 
while(source_file.at(i) != EOF) 
{ 
    // If not a tab or newline add to buffer 
    if (source_file.at(i) != "\n" || source_file.at(i) != "\t") 
    { 
     bufferList.add(source_file.at(i)); 
    } 
    i++; 
} 

會不會有信號的方式EOF就像我打開的文件那樣?

這或多或少是做什麼的總體綱要。我需要弄清楚一旦空了或者使用雙緩衝時如何補充緩衝區。我還需要弄清楚如何去掉以#開頭的評論。例如# This is a comment。我的掃描儀會看到#,然後刪除所有內容,直到獲得下一個換行符爲止。

+0

EOF表示您只是在文件末尾查找空值 –

+0

嘗試使用'std :: vector '作爲緩衝區,'istream :: read()'將數據讀入緩衝區。 –

+0

@ThomasMatthews將'istream :: read()'去掉空白? – GenericUser01

回答

0

嘗試這種情況:

char c; 
std::vector<char> buffer(1024); 
while (source_file.get(c)) 
{ 
    if ((c != '\n') || (c != '\t')) 
    { 
    buffer.push_back(c); 
    } 
} 

用於讀取數據的標準方法是,以測試用於在while循環讀出操作的結果。

對於塊寫,你可以做這樣的事情:

char buffer[1024]; 
while (source_file.read(buffer, sizeof(buffer)) 
{ 
    // Process the buffer here 
} 

您還應該使用std::istream::gcount()來從文件中讀取的字符數,因爲它可能是小於的緩衝區大小。

+0

我瞭解此答案的頂部。但是說'source_file.get(c)'與'source_file.at(c)'相比,它們有什麼區別嗎?還是它們是相同的?我想我只是困惑什麼'讀'做,以及如何使用它去除評論和壓縮空白。 – GenericUser01

+0

很抱歉,但我不明白的'在()'方法['標準:: istream'(http://en.cppreference.com/w/cpp/io/basic_istream)。 –

相關問題