#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;
}
我嘗試這樣做,但它不打印任何東西。爲什麼這不起作用?
您是否檢查了[this](http://www.cplusplus.com/doc/tutorial/files/)?它可能會讓你更好地理解。 – unexplored 2012-02-22 01:41:39