1.使用fread,fwrite完成两个文件之间的拷贝
程序代码:
#include <myhead.h>int main(int argc, const char *argv[])
{if(argc!=3){printf("input file error\n");printf("usage:./a.out srcfile destfile\n");return -1;}FILE *fp=NULL;if((fp=fopen(argv[1],"r"))==NULL){perror("fopen error");return -1;}char rbuf[128]="";FILE *fp1=NULL;if((fp1=fopen(argv[2],"w"))==NULL){perror("fopen error");return -1;}char buf[10]="";while(!feof(fp)){int ret=fread(buf,1,sizeof(buf),fp);fwrite(buf,1,ret,fp1);}fclose(fp);fclose(fp1);return 0;
}
运行结果:
2.使用read和write完成两个文件的拷贝
程序代码:
#include <myhead.h>
int main(int argc, const char *argv[])
{if(argc!=3){printf("input file error\n");printf("usage:./a.out srcfile destfile\n");return -1;}int fd=-1;if((fd=open(argv[1],O_RDONLY))==-1){perror("open error");return -1;}int fd1=-1;if((fd1=open(argv[2],O_CREAT|O_WRONLY,0664))==-1){perror("open error");return -1;}char rbuf[128]="";while(1){int res=read(fd,rbuf,sizeof(rbuf));if(res==0)break;write(fd1,rbuf,res);}close(fd);close(fd1);printf("拷贝成功\n");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;}char buf[128]=" ";int i=0;while(1){char *res=fgets(buf,sizeof(buf),fp);if(res==NULL){break;}i++;}int line=i+1;time_t sys_time=0;while(1){sys_time=time(NULL);struct tm *t=localtime(&sys_time);sprintf(buf,"%d:%4d-%02d-%02d %02d:%02d:%02d\n",line++,t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);sleep(1);printf("buf=%s",buf);fputs(buf,fp);fflush(fp);}fclose(fp);return 0;
}
运行结果: