【发布时间】:2010-07-25 02:01:24
【问题描述】:
我想打开一个文件并从中读取一行。文件中只有一行,所以我真的不需要担心循环,尽管为了将来参考,知道如何读取多行会很好。
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 中列出的入门书籍。
-
我没有 C++ 书籍。我在看cplusplus.com/reference/iostream/istream/getline,被
streamsize n参数弄糊涂了。 -
如果你点击
streamsize页面,它会说:“该类型是有符号基本整数类型之一的实现定义的同义词(通常有符号整数或有符号长整数)。”跨度> -
n是s指向的缓冲区的大小。如果您使用全局getline而不是成员getline,那么您不必担心该参数,因为全局getline读入std::string对象而不是缓冲区,而std::string对象可调整大小。