输出文本文档中指定的一行或多行(以换行符为界)

时间:2021-11-01 21:57:56
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 11

int isValid_data(char *);

int main(int argc, char *argv[])
{
	char *p, buf[MAX_NUM];
	char *date;
	FILE *pf;
	int flag = 0, fag = 0, ch = 0;
	int have_date = 0;

	if (argc < 3)
	{
		printf("Parameter is enough!\n");
		exit(1);
	}
/*
	if(	!isValid_data(argv[1]) )
	{
		printf("invalid data!\n");
		exit(1);
	}
*/

	if ((pf = fopen(argv[1], "r")) == NULL )
	{
		perror("argv[1]");
		exit(1);
	}

	date = argv[2];
/*
	flag = 1;
	while ((p = fgets(buf, MAX_NUM, pf)) != NULL)
	{
		if (flag == 0 || !strncmp(date, buf, 10))
		{	
			have_date = 1;
			fputs(buf, stdout);
			if (buf[strlen(buf) - 1] == '\n')
			{
				flag = 1;
			}
			else
			{
				flag = 0;
			}
		}
	}
*/
	flag =  1;
	fag = 1;
	while ((p = fgets(buf, MAX_NUM, pf)) != NULL)
	{
		if (flag == 0 || (fag == 1 && !strncmp(date, buf, 10)) )
		{
			have_date = 1;
			fputs(buf, stdout);
			if (buf[strlen(buf) - 1] == '\n')
			{
				flag = 1;
			}
			else 
			{
				flag = 0;
			}
		}
		else 
		{
			if (buf[strlen(buf) - 1] == '\n')
			{
				fag = 1;
			}
			else 
			{
				fag = 0;
			}
		}


		
	}



	if (have_date == 0)
	{
		printf("no error!\n");
	}
	fclose(pf);
	exit(0);
}