C++的文件读写比起C的要容易。C++进行文件读写涉及到的头文件有
<ifstream>: 文件读操作相关
<ofstream>:文件写操作相关
<fstream>:可以说是ifstream和ofstream的集合。
文件读操作:
用法跟cin差不多,只是输入流的来源不是终端,而是从本地资源。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream is("input.txt");
string s;
while (is >> s) {
cout << s << endl;
}
return 0;
}
input.txt:
a b
c d
output:
a
b
c
d
如果想读取正行,则需要使用getline.使用getline时,需要使用char数组,第二个参数是指每行读入多少个字符。#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
ifstream is("input.txt");
char in[100];
while (is.getline(in, strlen(in))) {
cout << in << endl;
}
return 0;
}
output:
a b
c d
文件写操作:
用法于cout差不多,cout 是把输出流输出到终端,这里是把输出流输出到本地存储。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream is("input.txt");
ofstream os("output.txt");
char in[100];
while (is.getline(in, 100)) {
os << in << endl;
}
return 0;
}
output.txt:
a b
c d
这里C++的读写操作就简单介绍到这里,这些用起来很容易上手。当然C++文件处理还有很多的函数调用,如read, write, peek, seekg, tellg等等,这些可以查看文档,推荐:http://www.cplusplus.com/reference/fstream/fstream/,这个在线文档关于c或C++的API很多有例子,这一点很不错。