using namespace std;
struct WebSites
{
string siteName;
int rank;
string getSiteName() { return siteName; }
int getRank() { return rank; }
WebSites(string const&, int);
WebSites();
};
WebSites::WebSites(string const& siteName, int rank) {
this->siteName = siteName;
this->rank = rank;
}
WebSites::WebSites() {}
ostream& operator << (ostream& stream, WebSites const& data) {
stream << data.rank << " " << data.siteName.size() << " " << data.siteName<< endl;
return stream;
}
istream& operator >> (istream& stream, WebSites data) {
stream >> data.siteName >> data.rank;
return stream;
}
int main() {
WebSites s1("www.google.co.uk", 1);
//write to file
ofstream writer("chou.dat", ios::out | ios::binary); //i'll add ios::app later
if (!writer) {
cout << " error opening file " << endl;
return -1;
}
else {
writer << s1.getSiteName() << " " << s1.getRank() << endl;
}
writer.close();
//read file
fstream writerR("chou.dat", ios::binary | ios::in | ios::ate);
WebSites read;
while (writerR >> read) {
cout << read.siteName << " rank: "<< read.rank << endl;
}
writerR.close();
return 0;
}
有人能告訴我爲什麼這個程序不會讀取並顯示控制檯文件?我的意思是它寫得很完美。我試着改變東西,但沒有任何工作我在網上查了類似的代碼,但仍然沒有。C++文件I/O我無法讀取.dat文件
'fstream的writerR' < - 如果這是讀書,爲什麼不'ifstream'? –
你爲什麼要調用一個閱讀流'writeR'?爲什麼不把它稱爲'reader'?在嘗試從中讀取文件之前,請務必檢查該文件是否已打開 – NathanOliver
不確定是否存在此問題,但是您將ios :: ate傳遞給導致文件尋找結尾的打開。從文件末尾沒有什麼可讀的。此外,我會假設它更好地使用輸入文件流(ifstream),並且您不能讀取整個結構,就像您單獨編寫每個字段時所嘗試的那樣。您指定二進制模式,但您的行爲就像是在傾銷文本。正如我所看到的,這段代碼沒有一個,只有幾個問題。 –