2014年01月13日 星期一 15:42
在C++标准库中,fstream模块提供了针对文件的读写操作方法。编程示例如下:
此代码使用了C++11标准,编译器必须使用-std=c++0x或者-std=c++11选项。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc,char **argv) {
string filename;
if(argc != 2) {
filename="/etc/passwd";
} else {
filename=argv[1];
}
cout << "filename: " << filename << endl;
ifstream ifs(filename,ifstream::in);
string line;
if(ifs) {
while(getline(ifs,line)) {
cout << line << endl;
}
ifs.close();
} else {
cerr << "can not open file: " << filename << endl;
}
return 0;
}
参考资料:
http://www.cplusplus.com/reference/fstream/ifstream/
Zeuux © 2025
京ICP备05028076号