2015-11-05 56 views
0
上寫的文件

我已經創建了一個函數來在文本文件上寫入一些數據,並且它工作正常。我創建了另一個函數來讀取文件的所有內容,併爲我打印出來!但是,由於某種原因它不起作用。任何人都可以幫忙嗎?我無法打印出我在

這是我的函數:

void myClass::displayFile() { 
    char line[LINE]; //to hold the current line 

    file.open("data.txt", ios::app); 

    //keep reading information from the file while the file is open and has data 
    while (!file.fail() && !file.eof()) { 
    int lineSize; //to loope through each line 

    file.getline(line, LINE); 
    lineSize = strlen(line); 

    //loop through the line to print it without delimiters 
    for (int i = 0; i < lineSize; ++i) { 
     if (line[i] == ';') { 
     cout << " || "; 
     } else { 
     cout << line[i]; 
     } 
    } 
    } 
    file.close(); 
    file.clear(); 

    if (file.fail()) { 
    cerr << "Something went wrong with the file!"; 
    } 
} 

注:該函數編譯和循環是可訪問的,但行字符串爲空。

是寫入功能:

void myClass::fileWriter() { 
    file.open("data.txt", ios::app); 
    file << name << ";" << age << ";" << "\n"; 
    file.close(); 
    file.clear(); 
} 
+1

我試過你的代碼在我的一個文件上,我可以看到它打印的內容..你可以檢查你的文件是否實際寫入正確 – Megha

+1

爲什麼你打開追加模式,你沒有寫入文件?爲什麼你使用不同的尺寸來聲明'line'和'getline'調用? ['std :: string'](http://en.cppreference.com/w/cpp/string/basic_string)和['std :: getline']有什麼問題(http://en.cppreference.com/ w/cpp/string/basic_string/getline)(它們更安全並且不容易出現緩衝區溢出)?在循環之後檢查'file.fail()',在檢查之前你明確地清除標誌是行不通的。 –

+0

哦,雖然[「爲什麼是」while(!feof(file))「總是錯誤的?」](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong )被標記爲C編程語言,但C++和相同的問題存在'while(!file.eof())'。 –

回答

0

我傻,你的問題的原因是盯着我的臉,從一開始就和它的app開模這就是問題所在。它是在中打開文件模式,這意味着你無法讀取它。

即使您可以從文件中讀取,光標也會放置在文件末尾,eofbit標誌本來會在第一次迭代中設置。

如果你想從一個文件中讀取,然後要麼使用std::ifstream自動設置in模式如果不指定模式,或者你要打開時明確設置in模式。

+0

是真的!在你告訴我它是寫在一個文件上後,我試圖刪除它,然後我的代碼工作得很好,我正準備在這裏宣佈它!但是,你明白了,謝謝 – Wilis1944