1、使用 fread 和 fwrite 完成文件拷贝
代码:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//判断终端输入
if(argc!=3)
{
printf("inputs file error\n");
printf("usage:./a.out srcfile destfile\n");
return -1;
}
//定义文件指针,以只读形式打开
FILE *srcfp = NULL;
if((srcfp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
//定义文件指针,以只写形式打开
FILE *destfp=NULL;
if((destfp=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
//拷贝
char buf[128]="";
int res = fread(buf,1,sizeof(buf),srcfp);
fwrite(buf,1,res,destfp);
//关闭文件
fclose(srcfp);
fclose(destfp);
return 0;
}
运行结果:
2、使用read和write完成文件的拷贝
代码:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//判断终端输入
if(argc!=3)
{
printf("inputs file error\n");
printf("usage:./a.out srcfile destfile\n");
return -1;
}
//定义文件描述符变量
int fd1 = -1;
//只读打开文件
if((fd1=open("./test.txt",O_RDONLY))==-1)
{
perror("open error");
return -1;
}
//定义文件描述符变量
int fd2 = -1;
//只写打开文件
if((fd2=open("./aa.txt",O_WRONLY | O_CREAT,0664))==-1)
{
perror("open error");
return -1;
}
//拷贝
char buf[128]="";
int res=read(fd1,buf,sizeof(buf));
write(fd2,buf,res);
return 0;
}
运行结果:
3、将时间在文件中跑起来
代码:
#include<myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
if((fp=fopen("./time.txt","a+"))==NULL)
{
perror("fopen error");
return -1;
}
int line =1;
int c=0;
while(1)
{
c=getc(fp);
if(c=='\n')
line++;
if(c==EOF)
break;
}
char time_buf[128]="";
time_t old_time,systime;
struct tm *t;
while(1)
{
systime=time(NULL);
if(old_time!=systime)
{
old_time=systime;
t=localtime(&systime);
snprintf(time_buf,sizeof(time_buf),"%d:%2d:%2d:%2d\n",\
line,t->tm_hour,t->tm_min,t->tm_sec);
printf("%s\n",time_buf);
fputs(time_buf,fp);
line++;
fflush(fp);
}
}
fclose(fp);
return 0;
}
运行结果:
4、用fread和fwrite完成图片的拷贝
代码:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//只读打开
FILE *fp1=NULL;
if((fp1=fopen("./picture.bmp","r"))==NULL)
{
perror("fopen error");
return -1;
}
//只写打开
FILE *fp2=NULL;
if((fp2=fopen("./cp.bmp","w"))==NULL)
{
perror("fopen error");
return -1;
}
//定义元素存储数据
char buf;
while(1)
{
fread(&buf,1,1,fp1); //从指定文件中读取数据
fwrite(&buf,1,1,fp2); //把数据写入指定文件
//判断文件是否读取结束
if(feof(fp1)||ferror(fp1))
{
break;
}
}
//关闭文件
fclose(fp1);
fclose(fp2);
return 0;
}
运行结果: