《C程序设计语言》------练习7-7、7-8

练习7-7:

修改第5章的模式查找程序,使它从一个命名文件的集合中读取输入(文件名参数),如果没有文件名参数,则从标准输入中读取输入。当发现一个匹配行时,是否将相应的文件名打印出来:

#include <stdio.h>
#include <string.h>
#define MAXLINE 1000

int getlinen(char *line, int max); /*输入行*/

main(int argc, char *argv[])
{
char line[MAXLINE];
long lineno = 0; /*记录行号*/
int c, except = 0, number = 0, found; /*except = 1为 -x模式,记录除匹配行之外的行;number = 1为-n模式,记录行号;found = 1为找到匹配*/
FILE *fp;
char *word; /*记录查找的单词*/
int file = 0; /*file = 1表示有输入文件*/

while (--argc > 0 && (*++argv)[0] == '-')
while (c = *++argv[0])
switch (c) {
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("find: illegal option %c\n", c);
argc = 0;
found = -1;
break;
}
if (argc != 1)
printf("Usage: find -x -n pattern\n");
word = *argv;
while ((fp = fopen(*++argv, "r")) != NULL) {
found = 0;
while (fgets(line, MAXLINE, fp) != NULL) {
lineno++;
if ((strstr(line, word) != NULL) != except) {
if (number)
printf("%ld:", lineno);
printf("%s", line);
}
if (strstr(line, word) != NULL)
found++;
}
if (found)
printf("The matched filename is %s\n", *argv);
file = 1;
fclose(fp);
}
if (!file) {
printf("no files!\n");
while (getlinen(line, MAXLINE) > 0) {
lineno++;
if ((strstr(line, word) != NULL) != except) {
if (number)
printf("%ld:", lineno);
printf("%s\n", *argv);
printf("%s", line);
}
}
}
if (!found)
printf("no files matched!\n");
}

int getlinen(char *line, int max)
{
int c;
char *t;

t = line;
while ((c = getchar()) != EOF && --max > 0 && c != '\n')
*line++ = c;
if (c == '\n')
*line++ = c;
*line = '\0';
return line - t;
}


练习7-8:

编写一个程序,以打印一个文件集合,每个文件从新的一页开始打印,并且打印每个文件相应的标题和页数。

 1 #include <stdio.h>
2 #define MAXLINE 1000
3
4 main(int argc, char *argv[])
5 {
6 char line[MAXLINE];
7 long lineno = 0; /*记录行号*/
8 FILE *fp;
9
10 if (--argc > 0) {
11 while ((fp = fopen(*++argv, "r")) != NULL) {
12 while (fgets(line, MAXLINE, fp) != NULL) {
13 if (!lineno) {
14 fprintf(stdout, "title: %s", line); /*打印标题*/
15 lineno++;
16 }
17 else {
18 fprintf(stdout, "%ld: ", lineno); /*打印行号*/
19 lineno++;
20 fprintf(stdout, "%s", line); /*打印行*/
21 }
22 }
23 lineno = 0;
24 fclose(fp);
25 }
26 }
27 else {
28 fprintf(stderr, "no files!\n");
29 exit(1);
30 }
31 }

如果在终端翻页,可加上:

system("clear");



posted on 2012-04-03 16:42  初级业余程序员  阅读(432)  评论(0编辑  收藏  举报

导航