IO进程线程0728作业-洪庆乐

要求创建一个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退出程序,过一会儿之后重新启动程序

main.c :

#include <stdio.h>
#include <time.h>
#include <unistd.h>

#define MSG_error(msg) {\
	fprintf(stdout,"line:%d",__LINE__); \
	perror(msg);\
	return -1; }
int file_line(FILE* fp)
{
    int line = 1;
    int c = 0;
    while((c = fgetc(fp)) != EOF)
    {
        if('\n' == c)
        {
            line++;
        }
    }
    return line;
}

int main(int argc, const char *argv[])
{
	FILE *fp = fopen("./time.txt","a+");
	if(NULL == fp)
	{
		MSG_error("fopen");
	}

	time_t t;
	int line = file_line(fp);
	while(1)
	{
		
		t = time(NULL);
		struct tm *info = NULL;
		info = localtime(&t);
		fprintf(fp,"[%d] %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);
		line++;
		sleep(1);
	}

	fclose(fp);
	return 0;
}

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

main.c:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#define MSG_error(msg) { \
	fprintf(stdout,"line:%d",__LINE__);\
	perror(msg);\
	return -1;\
}


int main(int argc, const char *argv[])
{
	int pc1 = open("./1.jpg",O_RDONLY);
	if(pc1 < 0)
	{
		MSG_error("open");
	}
	int pc2 = open("./copy.jpg",O_RDWR|O_TRUNC|O_CREAT,0777);
	if(pc2 < 0)
	{
		MSG_error("open");
	}

	char srr[20];
	ssize_t res = 0;
	while(1)
	{
		bzero(srr,sizeof(srr));
		res = read(pc1,srr,sizeof(srr));
		if(0 == res)
		{
			break;
		}
		write(pc2,srr,res);
	}



	if(close(pc1) < 0)
	{
		MSG_error("close");
	}
	if(close(pc2) < 0)
	{
		MSG_error("close");
	}
	printf("关闭成功\n");
	return 0;
}

 

 要求标准IO拷贝一张图片; eog 4.png

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MSG_error(msg) { \
	fprintf(stdout,"line:%d",__LINE__);\
	perror(msg);\
	return -1;\
}


int main(int argc, const char *argv[])
{
	FILE* pc1 = fopen("./1.jpg","r");
	if(pc1 == NULL)
	{
		MSG_error("fopen");
	}
	FILE* pc2 = fopen("./copy2.jpg","w+");
	if(pc2 == NULL)
	{
		MSG_error("fopen");
	}

	char srr[20];
	size_t res = 0;
	while(1)
	{
		bzero(srr,sizeof(srr));
		res = fread(srr,sizeof(char),20,pc1);
		if(0 == res)
		{
			break;
		}
		fwrite(srr,sizeof(char),20,pc2);
	}



	if(fclose(pc1) < 0)
	{
		MSG_error("close");
	}
	if(fclose(pc2) < 0)
	{
		MSG_error("close");
	}
	printf("关闭成功\n");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值