7.28-IO进程线程-作业

 1.要求创建一个time.txt,存储时间格式

#include <stdio.h>
#include <time.h>
#include <stdlib.h>     
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int file_line(FILE *fp)
{
	if(NULL == fp)
	{
		perror("fopen");
		return -1;
	}

	int count = 0;
	char c;
	while((c=fgetc(fp))!=-1)
	{
		if(c=='\n')
		{
			count++;
		}
	}
	return count;
}

int main(int argc, const char *argv[])
{
	FILE* fp = fopen("./time.txt","a+");	
	if(NULL == fp)
	{
		perror("open");
		return -1;
	}
	time_t t;
	struct tm *info;
	int line = file_line(fp) + 1;//获取行号
	while(1)
	{
		t = time(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);
		printf("已写入%d行\r",line);
		line++;
		fflush(fp);
		fflush(stdout);
		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 fd_r = open("./1.jpg",O_RDONLY);
	if(fd_r < 0)
	{
		MSG_ERR("open");
		return 1;
	}
	int fd_w = open("./2.jpg",O_RDWR|O_CREAT|O_TRUNC,0660);
	if(fd_w < 0)
	{
		MSG_ERR("open");
		return -1;
	}
	
	char c;
	int res;
	while(1)
	{
		res = read(fd_r,&c,sizeof(c));
		if(res==0)
		{
			break;
		}
		write(fd_w,&c,res);
	}
	printf("图片复制成功\n");
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值