#include <stdio.h>
#include <string.h>
bool verifyArgs(int argc, char **args, char errmsg[]);
typedef enum {
OperTypeNone,
OperTypeChar, OperTypeWord, OperTypeLine
} OperType;
OperType getOperType(char *oper);
int countchar(FILE *file);
int countword(FILE *file);
int countline(FILE *file);
int main(int argc, char **args) {
char errmsg[25];
if (!verifyArgs(argc, args, errmsg)){
printf("%s", errmsg);
return 1;
}
// 读取文件
char *filename = args[2];
char *opertype = args[1];
FILE *file;
if ((file = fopen(filename, "r")) == NULL){
printf("文件 \"%s\" 没有找到!", filename);
return 2;
}
// 判断操作类型
switch (getOperType(opertype)){
case OperTypeChar:
printf("字符数为: %d", countchar(file));
break;
case OperTypeWord:
printf("单词数为: %d", countword(file));
break;
case OperTypeLine:
printf("行数为: %d", countline(file));
break;
default:
printf("不支持 \"%s\" 操作", opertype);
}
fclose(file);
return 0;
}
// 验证参数合法性
bool verifyArgs(int argc, char **args, char errmsg[]){
if (argc != 3){
strcpy(errmsg, "只能使用两个参数!");
return false;
}
return true;
}
OperType getOperType(char *oper){
if (strcmp(oper, "-c") == 0){
return OperTypeChar;
}
if (strcmp(oper, "-w") == 0){
return OperTypeWord;
}
if (strcmp(oper, "-l") == 0){
return OperTypeLine;
}
return OperTypeNone;
}
/**
* 文件操作, 根据不同的命令进行统计
* */
/**
* 统计字符数
* */
int countchar(FILE *file){
char ch = 0;
int count = 0;
while ((ch = fgetc(file)) != EOF){
if (ch != ‘\n‘ && ch != ‘ ‘) count ++;
}
return count;
}
/**
* 统计单词数
* */
int countword(FILE *file){
int count = 0;
char ch = 0;
bool wordbegin = true;
while ((ch = fgetc(file)) != EOF){
if (ch == ‘\n‘ || ch == ‘ ‘){
wordbegin = true;
} else if (wordbegin == true){
count ++;
wordbegin = false;
}
}
return count;
}
/**
* 统计行数
* */
int countline(FILE *file){
int count = 0;
char line[100];
while (fgets(line, 100, file) != NULL){
count ++;
}
return count;
}
原文:http://www.cnblogs.com/jy10/p/5971443.html