#include<myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp;
if((fp=fopen("./time.txt","a+"))==NULL)
{
perror("fopen error");
return -1;
}
char buf;
int line=1;
while((buf=fgetc(fp))!=EOF)
{
if(buf=='\n')
{
line++;
}
}
while(1)
{
time_t sysTime=time(NULL);
struct tm *tm_ptr=localtime(&sysTime);
fprintf(fp,"%d、%2d:%2d:%2d\n",line,tm_ptr->tm_hour,tm_ptr->tm_min,tm_ptr->tm_sec);
line++;
sleep(1);
}
fclose(fp);
return 0;
}
使用fread、fwrite完成两个文件的拷贝
#include<myhead.h>
int main(int argc, char const *argv[]){
if(argc!=3){
printf("input file error\n");printf("usage: ./cope srcfile destfile\n");
return -1;
}
FILE *srcfp,*destfp; //定义一个文件指针
if ((srcfp=fopen(argv[1],"r"))==NULL)
{
perror("srcfile open error");return -1;
}
if ((destfp=fopen(argv[2],"w"))==NULL)
{
perror("destfile open error");return -1;
}
char buf[10]={0};
while (1)
{
int ret=fread(buf,1,sizeof(buf),srcfp);fwrite(buf,1,ret,destfp);
if(feof(srcfp)){
printf("拷贝成功\n");break;
}
if(ferror(srcfp)){
printf("出现了错误\n");break;
}
}
fclose(srcfp); //关闭fp指针打开的文件
fclose(destfp);
return 0;
}
ubuntu@ubuntu:day2$ cat 04test.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
if(argc!=3){
printf("input file error\n");
printf("usage: ./cope srcfile destfile\n");
return -1;
}
FILE *srcfp,*destfp; //定义一个文件指针
if ((srcfp=fopen(argv[1],"r"))==NULL)
{
perror("srcfile open error");
return -1;
}
if ((destfp=fopen(argv[2],"w"))==NULL)
{
perror("destfile open error");
return -1;
}
char buf[10]={0};
while (1)
{
int ret=fread(buf,1,sizeof(buf),srcfp);
fwrite(buf,1,ret,destfp);
if(feof(srcfp)){
printf("拷贝成功\n");
break;
}
if(ferror(srcfp)){
printf("出现了错误\n");
break;
}
}
fclose(srcfp); //关闭fp指针打开的文件
fclose(destfp);
return 0;
}