7.28 IO进程线程之时间相关函数与文件IO函数的使用

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>
#define MSG_ERR(msg) do{ \
fprintf(stderr,"line: %d ", __LINE__); \
perror(msg);\
}while(0)

int main(int argc, const char *argv[])
{
	FILE* fp = fopen("./time.txt","a+");
	if(NULL == fp)
	{
		MSG_ERR("fopen");
		return -1;
	}
	printf("fopen success\n");
	char c;
	int line=1;
	while((c=fgetc(fp))!=-1)
	{
		if(c==10)
			line++;
	}
	time_t t;
	//time(&t);
	struct tm* info = NULL;
	while(1)
	{
		t = time(&t);
		info = localtime(&t);
		fprintf(fp,"[%02d] %d-%02d-%02d %02d:%02d:%02d\n",\
				line++,info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
				info->tm_hour,info->tm_min,info->tm_sec);
		fflush(fp);
		sleep(1);
	}
	if(fclose(fp) < 0)
	{
		MSG_ERR("fclose");
		return -1;
	}
	printf("fclose success\n");

	return 0;
}

测试结果

在这里插入图片描述

2. 要求文件IO拷贝一张图片; eog ***.png

完整代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MSG_ERR(msg) do{ \
fprintf(stderr,"line: %d ", __LINE__); \
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
	int fd_r = open("/home/ubuntu/Pictures/1.png",O_RDONLY);
	int fd_w = open("./copy.png",O_RDWR|O_CREAT|O_TRUNC,0777);
	if(fd_r<0)
	{
		MSG_ERR("open");
		return -1;
	}
	if(fd_w<0)
	{
		MSG_ERR("open");
		return -1;
	}
	char arr[100] = "";
	ssize_t res;
	while((res=read(fd_r,arr,100))>0)
	{
		write(fd_w,arr,res);
		bzero(arr,sizeof(arr));
	}
	close(fd_r);
	close(fd_w);
	return 0;
}

测试结果

在这里插入图片描述

3. 附加:用标准IO拷贝一张图片

完整代码

#include <stdio.h>
#include <string.h>
#define MSG_ERR(msg) do{ \
	fprintf(stderr,"line: %d ", __LINE__); \
	perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
	FILE* fp_r = fopen("/home/ubuntu/Pictures/1.png","r");
	if(NULL==fp_r)
	{
		MSG_ERR("fopen");
		return -1;
	}
	FILE* fp_w = fopen("./2.png","w+");
	if(NULL==fp_w)
	{
		MSG_ERR("fopen");
		return -1;
	}
	char c;
	while(fread(&c,1,1,fp_r)!=0)
	{
		fwrite(&c,1,1,fp_w);
	}
	fclose(fp_r);
	fclose(fp_w);
	return 0;
}

测试结果

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不知名社畜L

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值