C++复制文本文件,统计行数、字符数【最简写法】

VC环境中,文本文件换行是'\n'
使用读入字符是否等于'\n'做行判断
函数使用数组返回多个值
不能直接返回数组,要返回数组元素指针
关于openmode
是所有读写操作的基类ios_base的成员,其它所有继承类都拥有该成员,所以可以作为ios_base的成员by their name as members of ios_base (like ios_base::in) ,也可以作为具体使用的继承类或者实例对象的成员or by using any of their inherited classes or instantiated objects, like for example ios::ate or cout.out.

public member type
<ios> <iostream>
std:: ios_base ::openmode
Type for stream opening mode flags
Bitmask type to represent stream opening mode flags.

A value of this type can be any valid combination of the following member constants:

member constant opening mode
app(append) Set the stream's position indicator to the end of the stream before each output operation.
ate(at end) Set the stream's position indicator to the end of the stream on opening.
binary(binary) Consider stream as binary rather than text.
in(input) Allow input operations on the stream.
out(output) Allow output operations on the stream.
trunc(truncate) Any current content is discarded, assuming a length of zero on opening.

These constants are defined in the ios_base class as public members. Therefore, they can be referred to either directly by their name as members of ios_base (like ios_base::in) or by using any of their inherited classes or instantiated objects, like for example ios::ate or cout.out.

#include <iostream>
#include <fstream>

using namespace std;

int* copyFile(string in, string out)//不能直接返回数组,要返回数组元素指针
{
	ifstream inf;
	ofstream outf;
	inf.open(in);//默认的openmode是in,相当于inf.open(in, ifstream::in);
	outf.open(out);//默认的openmode是out,相当于inf.open(in, ofstream::out);

	int res[2] = { 0, 0 };//全局变量或者静态变量,自动初始化为0;局部变量则为随机数或栈中残留的数

	char c = inf.get();//获取第一个字符
	while (inf.good())//读取正确
	{
		outf.put(c);//写入字符
		c = inf.get();//获取字符

		if (c == '\n')
			res[0]++;//统计行数
		res[1]++;//统计字符数
	}

	inf.close();//关闭输入文件流
	return res;
}

int main()
{
	int* count=copyFile("input.txt", "output.txt");
	cout << "行数是:" << count[0] << " " << "字符数是:" << count[1] << endl;
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值