jjgfjbfjf\
This commit is contained in:
68
wcl.c
68
wcl.c
@@ -1,31 +1,6 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <ctype.h> // для isspace()
|
||||||
int count_lines(const char *filename) {
|
|
||||||
FILE *file = fopen(filename, "r");
|
|
||||||
if (file == NULL) {
|
|
||||||
fprintf(stderr, "wcl: ошибка: не удалось открыть файл '%s'\n", filename);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lines = 0;
|
|
||||||
int ch;
|
|
||||||
int last_char = '\n';
|
|
||||||
|
|
||||||
while ((ch = fgetc(file)) != EOF) {
|
|
||||||
if (ch == '\n') {
|
|
||||||
lines++;
|
|
||||||
}
|
|
||||||
last_char = ch;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (last_char != '\n' && last_char != EOF) {
|
|
||||||
lines++;
|
|
||||||
}
|
|
||||||
|
|
||||||
fclose(file);
|
|
||||||
return lines;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) {
|
||||||
if (argc < 2) {
|
if (argc < 2) {
|
||||||
@@ -34,10 +9,45 @@ int main(int argc, char *argv[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 1; i < argc; i++) {
|
for (int i = 1; i < argc; i++) {
|
||||||
int lines = count_lines(argv[i]);
|
FILE *file = fopen(argv[i], "r");
|
||||||
if (lines >= 0) {
|
if (file == NULL) {
|
||||||
printf("%d\t%s\n", lines, argv[i]);
|
fprintf(stderr, "wcl: ошибка: не удалось открыть файл '%s'\n", argv[i]);
|
||||||
|
continue; // следующий файл
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int lines = 0;
|
||||||
|
int words = 0;
|
||||||
|
int bytes = 0;
|
||||||
|
int ch;
|
||||||
|
int in_word = 0;
|
||||||
|
|
||||||
|
while ((ch = fgetc(file)) != EOF) {
|
||||||
|
bytes++; // подсчет байт
|
||||||
|
|
||||||
|
if (ch == '\n') {
|
||||||
|
lines++; // подсчет строк
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверка на границу слова
|
||||||
|
if (isspace(ch)) {
|
||||||
|
if (in_word) {
|
||||||
|
words++;
|
||||||
|
in_word = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
in_word = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если осталась незасчитанная часть слова
|
||||||
|
if (in_word) {
|
||||||
|
words++;
|
||||||
|
}
|
||||||
|
|
||||||
|
fclose(file);
|
||||||
|
|
||||||
|
// Вывод: строки, слова, байты, имя файла
|
||||||
|
printf("%d\t%d\t%d\t%s\n", lines, words, bytes, argv[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
Reference in New Issue
Block a user