20231229(IO)作业

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

int countLine(const char *fileName){
	FILE * fp=NULL;
	if((fp=fopen(fileName,"r"))==NULL){
		perror("function countLine fopen error");
		return -1;
	}
	char buf[5]="";
	char * s=0;
	int LineCount=0;

	while((s=fgets(buf,sizeof(buf),fp))!=NULL){
		int i=0;
		while(*(buf+i)!='\0'){
			if(*(buf+i)=='\n') LineCount++;
			i++;
		}
	}
	//printf("%s line count is %d\n",argv[1],LineCount);

	fclose(fp);
	return LineCount;
}

int fileCopy(char * srcFileName, char * destFileName){
	FILE *sfp=0,*dfp=0;
	if((sfp=fopen(srcFileName,"r"))==NULL){
		perror("fileCopy source file open error");
		return -1;
	}
	if((dfp=fopen(destFileName,"w"))==NULL){
		perror("fileCopy destination file open error");
		return -1;
	}
	
	char *s=0;
	char buf[5]="";
	while((s=fgets(buf,sizeof(buf),sfp))!=NULL){
		fputs(s,dfp);
	}
	fclose(dfp);
	fclose(sfp);
}

int printDateTimeToFile(char *fileName){
	FILE *fp=0;
	if((fp=fopen(fileName,"a"))==NULL){
		perror("printDateTimeToFile open file error");
		return -1;
	}

	char buf[50]="";
	int n=countLine(fileName);
	while(1){
		time_t sysTime=time(NULL);
		struct tm *st_localtime=localtime(&sysTime);
		sprintf(buf,"%06d:  %4d年%02d月%02d日 %02d:%02d:%02d\n",n++,st_localtime->tm_year+1900,st_localtime->tm_mon+1,st_localtime->tm_mday,st_localtime->tm_hour,st_localtime->tm_min,st_localtime->tm_sec);
		sleep(1);
		printf("%s\n",buf);
		fputs(buf,fp);
		fflush(fp);
	}
	fclose(fp);
	return 0;
}

int main(int argc, const char *argv[])
{
	if(argc!=2){
		printf("error: please enter one file name as argument\n");
		return -1;
	}
	//printf("%s line count is %d\n",argv[1],countLine(argv[1]));

	//fileCopy("./a.txt","./c.txt");

	printDateTimeToFile("d.txt");

	return 0;
}
1> 使用fgets统计一个文件的行号
2> 使用fgets、fputs完成两个文件的拷贝
3> 向文件中输出当前的系统时间
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值