c风格的
#include<stdio.h>
#define LEGNTH 1024
int main(int argc,char *argv[])
{
FILE *in,*out;
in = fopen(argv[1],"r")//打开文件
char buf[LEGNTH+1] = {0};
if(NULL == in)
{
printf("fopen for read error\n");
return 0;
}
out = fopen(argv[2],"w");
if(NULL == out)
{
printf("fopen for write error\n");
return 0;
}
fgets(buf,LEGNTH,in);//读取整行,带换行符
while(!feof(in))//判断是否读取到文件结尾
{
if(EOF == fputs(out,buf))//写文件
{
printf("fputs error\n");
return 0;
}
fgets(buf,LEGNTH,in);
}
return 0;
}
c++风格的
#include<iostream>
#include<ofstream>
#include<string.h>
using namespace std;
int main(int argc,char *argv[])
{
ifstream in;
in.open(argv[1],ios::in);
if(!in)
{
cout << "open for read error" << endl;
return 0;
}
ofstream out;
out.open(argv[2],ios::out);
if(!out)
{
cout << "open for write error" << endl;
return 0;
}
string s;
while(getline(in,s))//读取行,但没有换行符
{
if(in.eof())
{
in.close();
out.close();
return 0;
}
out << s << endl; //写文件时要手动换行
}
in.close();
out.close();
return 0;
}
系统调用的
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#define LEGNTH 1024
int main(int argc,char *argv[])
{
int in,out;
in = open(argv[1],O_RDONLY);//
char buf[LEGNTH+1] = {0};
if(in < 0)
{
perror("open for read error\n");
return 0;
}
out = open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);//写文件时,文件不存在则要用O_CREAT创建,且要指定S_IRUSR|S_IWUSR文件的权限
if(out < 0)
{
perror("open for write error\n");
return 0;
}
ssize_t ret = read(in,buf,LEGNTH);
ssize_t ret2;
while(ret != 0)
{
ret2 = write(out,buf,ret);
if(ret2 != ret)
{
perror("open for write error\n");
return 0;
}
ret = read(in,buf,LEGNTH);
}
close(in);
close(out);
return 0;
}
上述3个代码分别编译成fputs.exe,fstream.exe,read.exe,找一个大点的文件测试他们的效率
<mct>time fputs.exe tmp log
0.732u 0.624s 0:01.40 96.4% 0+0k 0+0io 0pf+0w
<mct>time fstream.exe tmp log
2.188u 9.004s 0:14.62 76.4% 0+0k 0+0io 0pf+0w
<mct>time read.exe tmp log
0.008u 0.480s 0:00.49 97.9% 0+0k 0+0io 0pf+0w
<mct>ls -l tmp
-rw-r----- 1 mct users 272629968 Aug 6 14:33 tmp
<mct>ls -hl tmp
-rw-r----- 1 mct users 261M Aug 6 14:33 tmp
文件为261M,可见系统调用最快用了0.49秒,c风格的其次用了1.4秒,c++最慢用了14.62秒
注意:在读写文件时,输入输出函数使用要对应,不能读用read,写用printf,风格要保持一致,否则会出现问题。