作业1:
要求创建一个time.txt,存储内容格式如下:
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08
ctrl + c退出程序,过一会儿之后重新启动程序
----------------------------------------------
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08 <-------------------
[4] 2022-07-28 17:16:31
[5] 2022-07-28 17:16:32
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
FILE *fp_w=fopen("./time.txt","a");
FILE *fp_r=fopen("./time.txt","r");
if(NULL==fp_w)
{
perror("fopen");
return -1;
}
//system("clear");
time_t t=0,t_new;
struct tm *info = NULL;
char arr[50]="";
int line=0;
while(fgets(arr,sizeof(arr),fp_r))
{
line++;
printf("%d:%s",line,arr);
}
while(1)
{
t_new = time(NULL);
if(t_new!=t)
{
t=t_new;
info = localtime(&t);
line++;
printf("%d:",line);
printf("%d-%02d-%02d %02d:%02d:%02d\n",
info->tm_year+1900, info->tm_mon+1, info->tm_mday,
info->tm_hour, info->tm_min, info->tm_sec);
fprintf(fp_w,"%02d-%02d-%02d %02d:%02d:%02d\n",
info->tm_year+1900,info->tm_mon+1,info->tm_mday,
info->tm_hour,info->tm_min,info->tm_sec);
}
//由于printf是行缓冲,上述没有满足任何一种刷新缓冲区的机制
//所有要用fflush强制刷新
fflush(stdout);
fflush(fp_w);
}
return 0;
}
测试结果:
作业2:要求文件IO拷贝一张图片; eog 4.png
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(int argc, const char *argv[])
{
int fd_w=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC);
int fd_r=open("./1.png",O_RDONLY);
if(fd_w<0 || fd_r<0)
{
perror("open");
return -1;
}
char arr[10]="";
while(1)
{
if(read(fd_r,arr,sizeof(arr))<sizeof(arr))break;
write(fd_w,arr,sizeof(arr));
}
write(fd_w,arr,strlen(arr));
close(fd_w);
close(fd_r);
return 0;
}