c++ 文件读写

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很多有例子,这一点很不错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值