第一章Linux标准IO编程

本文主要介绍了四个Linux标准IO编程的实例,包括mycp_1.c、mycp_2.c、mycp_3.c和timer_record,来源于华清远见的书籍。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码来自华清远见的书上例子

一.实例一

     mycp_1.c

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	FILE *fps, *fpd;
	int c;

	if (argc < 3)
	{
		printf("Usage : %s <src_file> <dst_file>\n", argv[0]);
		return -1;
	}

	if ((fps = fopen(argv[1], "r")) == NULL)
	{
		printf("fail to open %s : %s\n", argv[1], strerror(errno));
		return -1;
	}

	if ((fpd = fopen(argv[2], "w")) == NULL)
	{
		printf("fail to open %s : %s\n", argv[2], strerror(errno));
		return -1;
	}

	while ((c = fgetc(fps)) != EOF)
	{
		fputc(c, fpd);
	}

	fclose(fps);
	fclose(fpd);

	return 0;
}


 

二.实例二

     mycp_2.c

#include <stdio.h>
#include <string.h>
#include <errno.h>

#define N 64

int main(int argc, char *argv[])
{
	FILE *fps, *fpd;
	char buf[N];

	if (argc < 3)
	{
		printf("Usage : %s <src_file> <dst_file>\n", argv[0]);
		return -1;
	}

	if ((fps = fopen(argv[1], "r")) == NULL)
	{
		printf("fail to open %s : %s\n", argv[1], strerror(errno));
		return -1;
	}

	if ((fpd = fopen(argv[2], "w")) == NULL)
	{
		printf("fail to open %s : %s\n", argv[2], strerror(errno));
		return -1;
	}

	while (fgets(buf, N, fps) != NULL)
	{
		fputs(buf, fpd);
	}

	fclose(fps);
	fclose(fpd);

	return 0;
}


 

三.实例三

      mycp_3.c

#include <stdio.h>
#include <string.h>
#include <errno.h>

#define N 64

int main(int argc, char *argv[])
{
	FILE *fps, *fpd;
	char buf[N];
	int n;

	if (argc < 3)
	{
		printf("Usage : %s <src_file> <dst_file>\n", argv[0]);
		return -1;
	}

	if ((fps = fopen(argv[1], "r")) == NULL)
	{
		printf("fail to open %s : %s\n", argv[1], strerror(errno));
		return -1;
	}

	if ((fpd = fopen(argv[2], "w")) == NULL)
	{
		printf("fail to open %s : %s\n", argv[2], strerror(errno));
		return -1;
	}

	while ((n = fread(buf, 1, N, fps)) > 0)
	{
		fwrite(buf, 1, n, fpd);
	}

	fclose(fps);
	fclose(fpd);

	return 0;
}


四.实例四

          timer_record

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

#define N 64

int main(int argc, char *argv[])
{
	FILE *fp;
	time_t t;
	struct tm *tp;
	char buf[N];
	int line = 0;

	if (argc < 2)
	{
		printf("Usage : %s <file>\n", argv[0]);
		return -1;
	}

	if ((fp = fopen(argv[1], "a+")) == NULL)
	{
		perror("fail to fopen");
		return -1;
	}

	while (fgets(buf, N, fp) != NULL)
	{
		if (buf[strlen(buf)-1] == '\n') line++;
	}

	while ( 1 )
	{
		time(&t);
		tp = localtime(&t);
		fprintf(fp, "%d, %d-%d-%d %d:%d:%d\n", ++line, tp->tm_year+1900, tp->tm_mon+1,
											   tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec);
		fflush(fp);
		sleep(1);
	}

	return 0;
}


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值