作者在 2013-05-12 15:32:54 发布以下内容
/*
编写一段程序,将一个字符, 零个或多个文件名作为命令行参数.
如果字符后没有参数跟随,程序读取标准输入文件.
否则,程序依次打开每个文件,然后报告每个文件中该字符的出现次数.
文件名和字符本身也与计数值一起报告.
程序中包括错误检查,以确定参数数目是否正确和是否能打开文件.
如果不能打开文件,程序要报告这一情况然后继续处理下一文件.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 40
void input(char *, char **);
void savename(int, char **, char *);
void search(char, FILE *, char *);
int main(int argc, char **argv)
{
char file[SIZE];
switch(argc){
case 1:exit(1);
case 2:input(file, argv);break;
default:savename(argc, argv, file);break;
}
puts("Done.");
return 0;
}
void input(char *file, char **argv)
{
FILE *fp;
printf("Enter file name (newline to quit): ");
while(scanf("%s", file) && file[0] != '\n')
{
if((fp = fopen(file, "r")) == NULL)
{
fprintf(stderr, "Can't open file %s.\n", file);
printf("Enter file name (newline to quit): ");
continue;
}
search(*argv[1], fp, file);
fclose(fp);
printf("Next file name (newline to quit): ");
}
}
void savename(int n, char **source, char *file)
{
int i = 2;
FILE * fp;
while(i < n)
{
file = source[i++];
if((fp = fopen(file, "r")) == NULL)
{
fprintf(stderr, "Can't open file %s.\n", file);
continue;
}
search(*source[1], fp, file);
fclose(fp);
}
}
void search(char ch, FILE * fp, char *file)
{
char s;
unsigned int count = 0;
while((s = fgetc(fp)) != EOF)
{
if(s == ch)
count++;
}
fprintf(stdout, "file: %s. %c sum = %u\n", file, ch, count);
}