【IO】学习成果day2

1.获取系统当前运行时间每秒输入到一个文件中,并在行前输入行号,并且重新我运行文件时追加进去。

linux@linux:~/study/IO/day2$ cat work1.c
#include<myhead.h>

int main(int argc, const char *argv[])
{
	//打开一个文件
	FILE *fp1;
	fp1=fopen("work1.txt","r");
	//记录行数
	int count=1;
	//读取文件中的字符,并判断是否为换行
	char buf[900];
	while((fgets(buf,sizeof(buf),fp1))!=NULL)
	{
		if(buf[strlen(buf)-1]=='\n')
		{
			count++;
		}
	}

	FILE *fp;
	fp=fopen("work1.txt","a");
	//无限循环
	while(1){
		//定义一个系统时间变量
		time_t sysTime=time(NULL);

		//定义时间结构体指针,指向时间
		struct tm *tm_ptr = localtime(&sysTime);
	

		fprintf(fp,"%d %4d-%2d-%2d-%02d-%02d:%02d\n",count,\
			tm_ptr->tm_year,\
			tm_ptr->tm_mon+1,\
			tm_ptr->tm_mday,\
			tm_ptr->tm_hour,\
			tm_ptr->tm_min,\
			tm_ptr->tm_sec);
		fflush(fp);
		sleep(1);
		count++;
	}


	//关闭文件
	fclose(fp);
	fclose(fp1);
	
	return 0;
}

运行结果

linux@linux:~/study/IO/day2$ gcc work1.c
linux@linux:~/study/IO/day2$ ./a.out 
^C
linux@linux:~/study/IO/day2$ cat work1.txt 
1  123- 8-16-21-45:46
2  123- 8-16-21-45:47
3  123- 8-16-21-45:48
4  123- 8-16-21-45:49
5  123- 8-17-18-39:05
6  123- 8-17-18-39:06
7  123- 8-17-18-39:07
8  123- 8-17-18-39:08
9  123- 8-17-18-39:09
10  123- 8-17-18-39:10
linux@linux:~/study/IO/day2$ ./a.out 
^C
linux@linux:~/study/IO/day2$ cat work1.txt 
1  123- 8-16-21-45:46
2  123- 8-16-21-45:47
3  123- 8-16-21-45:48
4  123- 8-16-21-45:49
5  123- 8-17-18-39:05
6  123- 8-17-18-39:06
7  123- 8-17-18-39:07
8  123- 8-17-18-39:08
9  123- 8-17-18-39:09
10  123- 8-17-18-39:10
11  123- 8-17-18-41:20
12  123- 8-17-18-41:21
13  123- 8-17-18-41:22
14  123- 8-17-18-41:23
15  123- 8-17-18-41:24
linux@linux:~/study/IO/day2$ cat work2.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, const char *argv[])
{
	//判断是否传入两个文件
	if(argc!=3)
	{
		printf("input file error\n");
		printf("usage:./a.out srcfile datfile\n");
		return -1;
	}
	//以只读的形式打开源文件
	FILE *srcfp;
	if((srcfp=fopen(argv[1],"r"))==NULL)
	{
		perror("dstfile open error");
		return -1;
	}

	
	//以只写的形式打开目标文件
	FILE *dstfp;
	if((dstfp=fopen(argv[2],"w"))==NULL)
	{
		perror("dstfile open error");
		return -1;
	}

	//定义搬运工
	char buf[999];
	while((fread(buf,sizeof(char),1,srcfp))!=0)
	{
		//将数据写入目标文件
		fwrite(buf,sizeof(char),1,dstfp);
	}
	//关闭文件指针
	fclose(srcfp);
	fclose(dstfp);

	printf("拷贝成功\n");

	return 0;
}

运行结果:

linux@linux:~/study/IO/day2$ gcc work2.c 
linux@linux:~/study/IO/day2$ ./a.out 01test.txt work2.txt
拷贝成功
linux@linux:~/study/IO/day2$ cat work2.txt 
hello world

3.思维导图
IO学习day2

文件IO1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值