BUPT-homework/semester2/pset3/1-filesOps.c
2022-04-03 23:22:03 +08:00

112 lines
1.9 KiB
C

#include <stdio.h>
#define FILENAME dict.dic
#define BUFLEN 65535
void countChar(FILE *fp);
void countLines(FILE *fp);
void countCaps(FILE *fp);
int main(void) {
FILE *fp = fopen("dict.dic", "r");
int op;
scanf("%d", &op);
switch (op) {
case (1): {
countChar(fp);
break;
}
case (2): {
countLines(fp);
break;
}
case (3): {
countCaps(fp);
break;
}
default: {
break;
}
}
fclose(fp);
return 0;
}
void countChar(FILE *fp) {
int cap = 0, low = 0, digits = 0, others = 0;
char buf;
while ((buf = fgetc(fp)) != EOF) {
if (buf >= 'A' && buf <= 'Z') {
cap++;
} else if (buf >= 'a' && buf <= 'z') {
low++;
} else if (buf >= '0' && buf <= '9') {
digits++;
} else {
others++;
}
}
printf("Task1:\n");
printf("capital: %d\n", cap);
printf("lowercase: %d\n", low);
printf("digit: %d\n", digits);
printf("others: %d\n", others);
}
void countLines(FILE *fp) {
int lines = 0;
int maxlen, minlen;
int i;
char buf[BUFLEN];
// Firstly read one line
fgets(buf, BUFLEN * sizeof(buf[0]), fp);
lines++;
for (i = 0; buf[i] != '\n'; i++) {
}
maxlen = i;
minlen = i;
while (fgets(buf, sizeof(buf), fp) != NULL) {
lines++;
for (i = 0; buf[i] != '\n'; i++) {
}
if (i > maxlen) {
maxlen = i;
}
if (i < minlen) {
minlen = i;
}
}
printf("Task2:\n");
printf("line: %d\n", lines);
printf("%d characters in max line.\n", maxlen);
printf("%d characters in min line.\n", minlen);
}
void countCaps(FILE *fp) {
char low[26] = {};
char cap[26] = {};
char buf;
while ((buf = fgetc(fp)) != EOF) {
if (buf >= 'a' && buf <= 'z') {
low[buf - 'a']++;
} else if (buf >= 'A' && buf <= 'Z') {
cap[buf - 'A']++;
}
}
printf("Task3:\n");
printf("CAPITAL:\n");
for (int i = 0; i < 26; i++) {
printf("%c:%d\n", i + 'A', cap[i]);
}
printf("LOWERCASE:\n");
for (int i = 0; i < 26; i++) {
printf("%c:%d\n", i + 'a', low[i]);
}
}