作业:
1>获取系统时间并写入文件,在停止程序后,再次运行程序,行号与前面行号相连
2> 使用fread、fwrite完成两个文件的拷贝
1:
#include <myhead.h>
#include <time.h>
int get_line(FILE *fp)
{
//获取行号
char buf[5];
int count=0;
while(fgets(buf,sizeof(buf),fp)!=NULL)
{
if(buf[strlen(buf)-1]=='\n')
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
//打开文件
FILE *fp;
if((fp=fopen("./time.txt","a+"))==NULL)
{
perror("fopen error");
return -1;
}
//定义一个系统时间变量
time_t sysTime = time(NULL);
int line=get_line(fp);
while(1)
{
time(&sysTime);
struct tm *tm_ptr=localtime(&sysTime);
line++;
fprintf(fp,"[%d] %4d-%d-%2d %02d:%02d:%02d\n",\
line,\
tm_ptr->tm_year+1900,\
tm_ptr->tm_mon+1,\
tm_ptr->tm_mday,\
tm_ptr->tm_hour,\
tm_ptr->tm_min,\
tm_ptr->tm_sec);
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
结果1:
结果2:
2:
#include <myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp_y;
if((fp_y=fopen("./password.txt","r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp_c;
if((fp_c=fopen("./zuoye1.txt","w"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[100]={0};
while(1)
{
//置空数组
memset(buf,0,sizeof(buf));
//读取源文件内容
fread(buf,sizeof(buf),1,fp_y);
//将原文件写入新文件
fwrite(buf,sizeof(buf),1,fp_c);
//判断是否读取完成
if(feof(fp_y))
{
break;
}
if(ferror(fp_y))
{
break;
}
}
fclose(fp_y);
fclose(fp_c);
printf("拷贝成功!\n");
return 0;
}
结果:
思维导图:https://mubu.com/app/edit/home/6P1_TVHx6LD#m