要求创建一个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 <head.h>
int main(int argc, char const *argv[])
{
time_t t2;//long int t2
char buf[10];//读取的长度
FILE *fp, *lfp;//追加文件,读取文件
int a = 1;
if ((fp = fopen("./time.txt", "a")) == NULL)
PRINT_ERR("open file error");
//追加打开文件
if ((lfp = fopen("./time.txt", "r")) == NULL)
PRINT_ERR("open file error");
//只读打开文件
while (1)
{
time(&t2);//把秒数传给t2
struct tm *info = NULL;//转换秒数为时间的函数
info = localtime(&t2);
fflush(fp);//刷新缓冲区
while (fgets(buf, sizeof(buf), lfp) != NULL)//循环条件
{
if ((buf[strlen(buf) - 1]) == '\n')//判断行号
a++;
}
fprintf(fp, "[%d] %d-%02d-%02d-%02d-%02d-%02d\n", a,//打印时间
info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,
info->tm_hour, info->tm_min, info->tm_sec);
sleep(1);
}
fclose(fp);
fclose(lfp);
return 0;
}
1.用read和write拷贝一张图片
#include <head.h>
int main(int argc, char const *argv[])
{
int fd,lfd;//目标文件,源文件
if((fd=open("./1.bmp",O_RDONLY))==-1)//只读方式打开
PRINT_ERR("open file error");
if((lfd=open("./1copy.bmp",O_WRONLY|O_TRUNC|O_CREAT,0666))==-1)
//只写方式打开,文件不存在就创建,存在就清空,权限666(不加权限的话拷贝后的文件打不开)
PRINT_ERR("open file error");
char buf[128];
int ret;//接收读取返回值,读取多少字节就返回多少
while((ret=read(fd,buf,sizeof(buf)))>0)
write(lfd,buf,ret);//不能使用sizeof(buf),因为可能会越界
printf("拷贝成功\n");
close(fd);
return 0;
}