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>
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;
}