我想打開一個文件並從中讀取一行。文件中只有一行,所以我不需要擔心循環,但爲了將來的參考,知道如何讀取多行文件會很好。如何在C++中使用ifstream打開並讀取文件?
int main(int argc, const char* argv[]) {
// argv[1] holds the file name from the command prompt
int number = 0; // number must be positive!
// create input file stream and open file
ifstream ifs;
ifs.open(argv[1]);
if (ifs == NULL) {
// Unable to open file
exit(1);
} else {
// file opened
// read file and get number
...?
// done using file, close it
ifs.close();
}
}
我該怎麼做?另外,我是否正確處理打開文件是否成功?
謝謝。
您是否擁有C++書?如果是這樣,你看看它討論標準I/O庫的章節嗎?如果不是,我強烈建議您閱讀[The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/)中列出的介紹性書籍之一。 – 2010-07-25 02:04:51
我沒有C++書。我在看http://www.cplusplus.com/reference/iostream/istream/getline/,我被'streamsize n'參數搞糊塗了。 – Hristo 2010-07-25 02:29:53
如果你點擊'streamsize'頁面,它會說:「這個類型是一個實現定義的同義詞之一,它是一個有符號的基本整型(通常是帶符號的int或有符號的長整型)。」 – 2010-07-25 05:30:05