2012-02-22 106 views
1
#include <iostream> 
#include <fstream> 

int main() { 
    std::ofstream outfile("text.txt", ios::trunc); 
    std::ifstream infile("text.txt", ios::trunc); 

    outfile.seekp(0); 

    std::cout << "This is a file"; 

    infile.seekg(0, ios::end); 
    int length = infile.tellg(); 
    infile.read(0, length); 

    infile.close(); 
    outfile.close(); 
    return 0; 
} 

我想我背後有這個想法,但我覺得(我很確定)我不知道我在做什麼。我查過它,一切都讓我困惑。我已經閱讀了C++的參考資料,然後我使用了它,但我仍然不明白我做錯了什麼。我想設置一個文件流或類似的東西,但我很困惑,我應該做什麼

#include <iostream> 
#include <fstream> 
#include <cstring> 

int main() { 
    std::fstream file("text.txt", std::ios_base::in | std::ios_base::out); 

    file << "This is a file"; 
    int length = file.tellg(); 

    std::string uberstring; 
    file >> uberstring; 
    std::cout << uberstring; 

    char *buffer = new char[length + 1]; 
    file.read(buffer, length); 
    buffer[length] = '\0'; 

    file.close(); 
    delete [] buffer; 

    return 0; 
} 

我嘗試這樣做,但它不打印任何東西。爲什麼這不起作用?

+0

您是否檢查了[this](http://www.cplusplus.com/doc/tutorial/files/)?它可能會讓你更好地理解。 – unexplored 2012-02-22 01:41:39

回答

1

如果你想讀取和寫入同一個文件,只需要使用正常的std::fstream ...沒有必要嘗試和打開同一個文件作爲ifstreamofstream。另外,如果要將數據寫入文件,請在實際的fstream實例對象上使用operator<<,而不要使用std::cout ...,只需將它寫入std::cout(通常是控制檯)的任何位置即可。最後,對read的調用必須返回到緩衝區,不能使用NULL作爲參數。因此,您的代碼將更改爲以下內容:

int main() 
{ 
    std::fstream file("text.txt", ios_base::in | ios_base::out); 

    //outfile.seekp(0); <== not needed since you just opened the file 

    file << "This is a file"; //<== use the std::fstream instance "file" 

    //file.seekg(0, ios::end); <== not needed ... you're already at the end 
    int length = file.tellg(); 

    //you have to read back into a buffer 
    char* buffer = new char[length + 1]; 
    infile.read(buffer, length); 
    buffer[length] = '\0'; //<== NULL terminate the string 

    file.close(); 
    delete [] buffer; 

    return 0; 
} 
+0

非常感謝老兄。但是我有幾個關於代碼的問題。什麼是ios_base?這只是一個命名空間嗎?另外,當我用fstream打開文件流時,是否自動指向文件的結尾? – user1220165 2012-02-22 01:44:49

+0

@ user1220165:'ios_base'是一個類。顧名思義,它是其他流類的基類,包括'fstream'。 – 2012-02-22 01:54:49

+0

好的,謝謝老兄。 – user1220165 2012-02-22 01:57:16

相關問題