IO进程线程->文件IO->day2

目录

一、创建存储文件time.txt

1.1 要求创建一个time.txt,存储内容格式如下:

 2.2 函数代码

2.3 执行结果

二、要求文件IO拷贝一张图片; eog 1.png

2.1 函数代码

2.2 执行结果


 

一、创建存储文件time.txt

1.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

 2.2 函数代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>


int main(int argc, const char *argv[])
{
	FILE *a1=fopen("./time.txt","r+");
	if(a1 == NULL)
	{
		perror("open");
		return -1;
	}
	long flag=-1;
	while(1)
	{
		time_t t=time(NULL);
		struct tm *t_day=localtime(&t);
		while(1)
		{
			char arr[3]={0};
			int i=0;
			char *p=fgets(arr,sizeof(arr)-1,a1);
			while(arr[i] != '\0')
			{
				if(arr[i] == '\n'){
					flag++;
				}
				i++;
			}
			if(NULL == p)
			{
				break;
			}
		}
		fprintf(a1,"[%ld]  %d-%02d-%02d %02d:%02d:%02d\n",\
				flag,t_day->tm_year+1900,t_day->tm_mon,t_day->tm_mday,t_day->tm_hour,t_day->tm_min,t_day->tm_sec);
		fflush(a1);
		printf("存入成功\n");
		flag++;
		sleep(1);
	}
	fclose(a1);

	return 0;
}

2.3 执行结果

 


 

二、要求文件IO拷贝一张图片; eog 1.png

2.1 函数代码

#include <stdio.h>
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <string.h>

int main(int argc, const char *argv[])
{
	int fd_r=open("/home/ubuntu/图片/1.png",O_RDONLY);
	int fd_w=open("./cpy.png", O_WRONLY|O_CREAT|O_TRUNC, 0664);
	if(fd_r <0 && fd_w<0)
	{
		perror("open");
		return -1;
	}
	char buf[10];
	ssize_t res=0;
	while(1)
	{
		bzero(buf,sizeof(buf));
		res=read(fd_r,buf,sizeof(buf));
		if(0 == res)
		{
			break;
		}
		write(fd_w,buf,res);
	}
	close(fd_r);
	close(fd_w);
	printf("拷贝成功\n");
	return 0;
}

 

2.2 执行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值