统计文件字符信息
1 #include <stdio.h> 2 /** 3 @author tz 4 @date 2019-04-11 5 */ 6 void finishTask1(FILE* fptr); 7 void finishTask2(FILE* fptr); 8 void finishTask3(FILE* fptr); 9 10 int main() { 11 FILE* fptr = fopen("p1.txt", "r"); 12 if(fptr==NULL) 13 exit(0); 14 printf("The result is:\n"); 15 finishTask1(fptr); 16 rewind(fptr); 17 finishTask2(fptr); 18 rewind(fptr); 19 finishTask3(fptr); 20 rewind(fptr); 21 fclose(fptr); 22 } 23 24 //完成Task1,统计不同类字符数量 25 void finishTask1(FILE* fptr) { 26 printf("Task1:\n"); 27 int capital = 0, lowercase = 0, digit = 0, other = 0; 28 int ch = fgetc(fptr); 29 while (ch != EOF) { 30 if (ch >= 'A'&&ch <= 'Z') 31 capital++; 32 else if (ch >= 'a'&&ch <= 'z') 33 lowercase++; 34 else if (ch >= '0'&&ch <= '9') 35 digit++; 36 else 37 other++; 38 ch = fgetc(fptr); 39 } 40 41 printf("capital:%d\n", capital); 42 printf("lowercase:%d\n", lowercase); 43 printf("digit:%d\n", digit); 44 printf("others:%d\n\n", other); 45 } 46 47 //统计行数,行最大长度,行最小长度 48 void finishTask2(FILE* fptr) { 49 printf("Task2:\n"); 50 int ch = fgetc(fptr); 51 int totalLine = 0, maxLine = 0, minLine, curchars = 0, x = 0;//x用来判断是否是第一行 52 while (ch != EOF) { 53 while (ch != '\n') { 54 curchars++; 55 ch = fgetc(fptr); 56 if (ch == EOF) 57 break; 58 } 59 x++; 60 if (maxLine < curchars) 61 maxLine = curchars; 62 if (x == 1 || minLine > curchars) 63 minLine = curchars; 64 totalLine++; 65 curchars = 0; 66 ch = fgetc(fptr); 67 } 68 printf("line:%d\n", totalLine); 69 printf("%d characters in max line.\n", maxLine); 70 printf("%d characters in min line.\n\n", minLine); 71 } 72 73 //输出具体的大小写字母的统计信息 74 void finishTask3(FILE* fptr) { 75 printf("Task3:\n"); 76 int ch = getc(fptr), cap[26] = { 0 }, Low[26] = {0}; 77 int count = 0; 78 //统计大小写的个数,存放在数组中 79 while (ch != EOF) { 80 if (ch >= 'A'&&ch <= 'Z') { 81 cap[ch - 'A']++; 82 } 83 if (ch >= 'a'&&ch <= 'z') { 84 Low[ch - 'a']++; 85 } 86 ch = getc(fptr); 87 } 88 //依次输出 89 printf("CAPITAL:\n"); 90 while (count != 26) { 91 if ((count + 1) % 4 == 0) 92 printf("%c:%d\n", 'A' + count, cap[count]); 93 else 94 printf("%c:%d ", 'A' + count, cap[count]); 95 count++; 96 } 97 printf("\n"); 98 count = 0; 99 printf("LOWERCASE:\n"); 100 while (count != 26) { 101 if ((count + 1) % 4 == 0) 102 printf("%c:%d\n", 'a' + count, Low[count]); 103 else 104 printf("%c:%d ", 'a' + count, Low[count]); 105 count++; 106 } 107 printf("\n"); 108 }