获取系统时间,并将时间写入文件中
#include <stdio.h>
#include <string.h>
#include <time.h>
int main()
{
FILE *fp;
if((fp=fopen("./hw1.txt","w"))==NULL)
{
perror("file open");
return -1;
}
int i=1;//打印行号
time_t sys_time = time(NULL);
struct tm *lastTime = localtime(&sys_time);
int a=lastTime->tm_sec;//记录原有的时间
int now=0;
int count=0;//控制打印的个数
while(count!=10)
{
sys_time = time(NULL);
struct tm*nowTime = localtime(&sys_time);//申请新的时间
now=nowTime->tm_sec;
if(a!=now)//判断旧的时间和新的时间是否相等
{
fprintf(fp,"%5d、%4d/%2d/%2d %2d:%2d:%2d\n",i++,nowTime->tm_year+1900,nowTime->tm_mon+1,nowTime->tm_mday,nowTime->tm_hour,nowTime->tm_min,now);
count++;
a=now;//将旧的时间进行更新
}
}
return 0;
}
运行代码效果如下:
用fread、fwrite实现文件拷贝
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp1;
FILE *fp2;
if((fp1=fopen("./hw2.txt","w"))==NULL)
{
perror("file open");
return -1;
}
if((fp2=fopen("./hw21.txt","w"))==NULL)
{
perror("file open");
return -1;
}
char arr[20]="hello world";
char b[1024];
fwrite(arr,strlen(arr),1,fp1);
fclose(fp1);
FILE *fp3=fopen("./hw2.txt","r");
perror("fp3");
while(!feof(fp3))
{
fread(b,strlen(b),1,fp3);
fwrite(b,strlen(b),1,fp2);
}
return 0;
}
实现效果如下