作业7.28 文件IO与标准IO

这篇博客展示了如何使用C语言进行文件操作。首先,通过标准IO创建并追加time.txt文件,每秒记录当前时间,程序可通过Ctrl+C中断并重启后继续追加。其次,介绍了两种文件IO拷贝图片的方法,一种使用系统调用open、read、write和close,另一种使用标准库函数fopen、fread和fwrite,均能成功将图片从源路径复制到目标路径。
摘要由CSDN通过智能技术生成

1.使用标准IO完成time.txt

要求创建一个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 <unistd.h>
#include <time.h>
int main(int argc, const char *argv[])
{
	FILE *fp=fopen("./time.txt","a+");
	if(NULL==fp)
	{
		perror("fopen");
		return -1;
	}
	char a;
	int count=1;
	while((a=fgetc(fp))!=-1)
	{
		if(a=='\n')
		{
			count++;
		}
	}
	time_t t;
	struct tm *info=NULL;
	while(1)
	{
		t=time(NULL);
		info=localtime(&t);
		fprintf(fp,"[%02d] %d-%02d-%02d %02d:%02d:%02d\n", \
				count,info->tm_year+1900, info->tm_mon+1, info->tm_mday,\
				info->tm_hour, info->tm_min, info->tm_sec);
		count++;
		fflush(fp);
		sleep(1);
	}
	fclose(fp);
	return 0;
}

运行结果

在这里插入图片描述

2. 要求文件IO拷贝一张图片

代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.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[])
{
	
	int fd1=open("/home/ubuntu/图片/sllh.jpg",O_RDONLY);
	if(fd1<0)
	{
		MSG_ERR("open");
		return -1;
	}
	int fd2=open("./sllh.jpg",O_WRONLY|O_CREAT|O_TRUNC,0777);
	if(fd2<0)
	{
		MSG_ERR("open");
		return -1;
	}
	char buf[100];
	ssize_t c;
	while((c=read(fd1,buf,100))>0)
	{
		write(fd2,buf,c);
	}
	close(fd1);
	close(fd2);
	return 0;
}

运行结果

将/home/ubuntu/图片/sllh.jpg复制到当前目录

在这里插入图片描述

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

代码

#include <stdio.h>
#define MSG_ERR(msg) do{ \
    fprintf(stderr,"line: %d ", __LINE__); \
    perror(msg);\
}while(0)

int main(int argc, const char *argv[])
{
	
	FILE *fp1=fopen("/home/ubuntu/图片/sllh.jpg","r");
	if(fp1<0)
	{
		MSG_ERR("fopen");
		return -1;
	}
	FILE *fp2=fopen("./sllh.jpg","w+");
	if(fp2<0)
	{
		MSG_ERR("open");
		return -1;
	}
	char buf[100];
	size_t c;
	while((c=fread(buf,1,100,fp1))>0)
	{
		fwrite(buf,1,c,fp2);
	}
	fclose(fp1);
	fclose(fp2);
	return 0;
}

运行结果

将/home/ubuntu/图片/sllh.jpg复制到当前目录

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不知名大学生M

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

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

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

打赏作者

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

抵扣说明:

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

余额充值