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

来源:互联网 发布:新手淘宝客服简历表格 编辑:程序博客网 时间:2024/05/17 22:41
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.

以下摘至:http://www.cplusplus.com/reference/ios/ios_base/openmode/
public member type
<ios> <iostream>
std::ios_base::openmode
Type for stream opening mode flags
Bitmask type to represent streamopening mode flags.

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

member constantopening modeapp(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 theios_base class as public members. Therefore, they can be referred to either directly by their name as members of ios_base (likeios_base::in) or by using any of their inherited classes or instantiated objects, like for exampleios::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;}