BUPT-homework/semester2/pset3/1-filesOps.c

110 lines
1.9 KiB
C
Raw Normal View History

2022-04-03 23:22:03 +08:00
#include <stdio.h>
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) {
2022-06-02 11:59:54 +08:00
case (1): {
countChar(fp);
break;
}
case (2): {
countLines(fp);
break;
}
case (3): {
countCaps(fp);
break;
}
default: {
break;
}
2022-04-03 23:22:03 +08:00
}
fclose(fp);
return 0;
}
void countChar(FILE *fp) {
int cap = 0, low = 0, digits = 0, others = 0;
char buf;
2022-06-02 11:59:54 +08:00
while ((buf = getc(fp)) != EOF) {
2022-04-03 23:22:03 +08:00
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);
}
2022-06-02 11:59:54 +08:00
2022-04-03 23:22:03 +08:00
void countLines(FILE *fp) {
2022-06-02 11:59:54 +08:00
// Scan one line first
char buf;
2022-04-03 23:22:03 +08:00
int lines = 0;
2022-06-02 11:59:54 +08:00
int linemax = 0;
int linemin = 0;
int i = 0;
while ((buf = fgetc(fp)) != EOF) {
if (buf != '\n') {
i++;
} else {
if (lines == 0) {
linemax = i;
linemin = i;
} else {
if (i > linemax) {
linemax = i;
}
if (i < linemin) {
linemin = i;
}
}
lines++;
i = 0;
2022-04-03 23:22:03 +08:00
}
}
2022-06-02 11:59:54 +08:00
printf("Task2:\nline: %d\n%d characters in max line.\n%d characters in min "
"line.\n",
lines, linemax, linemin);
2022-04-03 23:22:03 +08:00
}
2022-06-02 11:59:54 +08:00
2022-04-03 23:22:03 +08:00
void countCaps(FILE *fp) {
2022-06-02 11:59:54 +08:00
int low[26] = {};
int cap[26] = {};
2022-04-03 23:22:03 +08:00
2022-06-02 11:59:54 +08:00
char buf;
while ((buf = fgetc(fp)) != EOF) {
if (buf >= 'a' && buf <= 'z') {
low[buf - 'a']++;
} else if (buf >= 'A' && buf <= 'Z') {
cap[buf - 'A']++;
}
}
2022-04-03 23:22:03 +08:00
2022-06-02 11:59:54 +08:00
printf("Task3:\n");
printf("CAPITAL:\n");
for (int i = 0; i < 26; i++) {
printf("%c:%d\n", i + 'A', cap[i]);
}
2022-04-03 23:22:03 +08:00
2022-06-02 11:59:54 +08:00
printf("LOWERCASE:\n");
for (int i = 0; i < 26; i++) {
printf("%c:%d\n", i + 'a', low[i]);
}
2022-04-03 23:22:03 +08:00
}