2012-02-22 14 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 + +のリファレンスを読んで、私はそれをgoogled、しかし私はまだ間違っていることを理解していない。私はファイルストリームなどを設定しようとしていますが、私は何をすべきかについて非常に混乱しています

#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

答えて

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

ありがとう。しかし、私はコードについてさらに2つの質問があります。 ios_baseとは何ですか?それは単に名前空間ですか?また、fstreamでファイルストリームを開くと、自動的にファイルの最後を指していますか? – user1220165

+0

@ user1220165: 'ios_base'はクラスです。名前が示すように、それは 'fstream'を含む他のストリームクラスの基本クラスです。 –

+0

よろしくお願いします。 – user1220165

関連する問題