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>
int main(int argc, const char *argv[])
{
//打开文件
FILE *fp=fopen("./time.txt","a+");
if(NULL==fp)
{
perror("fopen");
return -1;
}
int count=1;
char c;
while(1)
{
c=fgetc(fp);
if(c==-1)
{
break;
}
if(c=='\n')
{
count++;
}
}
while(1)
{
time_t t=time(NULL);
struct tm *p=NULL;
p=localtime(&t);
fprintf(fp,"[%d] %d-%02d-%02d %02d-%02d-%02d\n",\
count, p->tm_year+1900,p->tm_mon+1,p->tm_mday,\
p->tm_hour,p->tm_min,p->tm_sec);
fflush(fp);
count++;
sleep(1);
}
fclose(fp);
return 0;
}
ubuntu@ubuntu:2$ gcc time.c
ubuntu@ubuntu:2$ ./a.out
^C
ubuntu@ubuntu:2$ ./a.out
^C
ubuntu@ubuntu:2$ cat time.txt
[1] 2022-10-09 21-05-42
[2] 2022-10-09 21-05-43
[3] 2022-10-09 21-05-44
[4] 2022-10-09 21-05-45
[5] 2022-10-09 21-05-54
[6] 2022-10-09 21-05-55
[7] 2022-10-09 21-05-56
2.用read和write拷贝一张图片
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
//打开文件
int fd;
int dd;
if(fd<0)
{
perror("open");
return -1;
}
if(dd<0)
{
perror("open1");
return -1;
}
fd=open("./1.png",O_RDONLY);
dd=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
printf("%d\n",fd);
printf("%d\n",dd);
//读取图片
char buf[16]="";
ssize_t ret;
ssize_t res;
while(1)
{
ret=read(fd,buf,1);
if(ret==0)
{
break;
}
res=write(dd,buf,1);
if(res==-1)
{
break;
}
}
//关闭文件
if(close(fd)<0)
{
perror("close");
return -1;
}
if(close(dd)<0)
{
perror("close");
return -1;
}
return 0;
}
ubuntu@ubuntu:1$ diff 1.png 2.png