用c语言在当前目录下创建一个文件"record.txt",输入一些随机英文文本。然后输出该文件的最后5行,并统计这5行中单词的数量。
时间: 2024-03-01 17:55:19 浏览: 90
基于Python实现的一个命令行文本计数统计程序,可统计纯英文txt文本中的字符数,单词数,句子数,Python文件行数
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1024 // 最大行长度
#define MAX_WORD 100 // 最大单词长度
// 统计字符串中单词数量
int count_word(char* str) {
int count = 0;
int len = strlen(str);
int i = 0;
while (i < len) {
// 跳过空格
while (i < len && str[i] == ' ') {
i++;
}
if (i == len) {
break;
}
// 统计单词长度
int word_len = 0;
while (i < len && str[i] != ' ') {
word_len++;
i++;
}
count++;
}
return count;
}
int main() {
char filename[] = "record.txt";
FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("无法打开文件 %s\n", filename);
exit(1);
}
// 随机输入一些英文文本
char text[] = "Hello, world! This is a random text for testing.\n"
"I hope it's long enough to have more than 5 lines.\n"
"Let's count the number of words in the last 5 lines.\n"
"It shouldn't be too difficult if we use some basic string manipulation.\n"
"But we need to pay attention to various edge cases.\n"
"For example, what if a line contains only spaces or tabs?\n"
"What if the last line doesn't end with a newline character?\n"
"We need to handle them properly to get accurate results.\n"
"Anyway, let's give it a try and see if it works as expected.\n";
fputs(text, fp);
fclose(fp);
// 读取文件并统计单词数量
fp = fopen(filename, "r");
if (fp == NULL) {
printf("无法打开文件 %s\n", filename);
exit(1);
}
char lines[5][MAX_LINE];
int line_count = 0;
int word_count = 0;
while (fgets(lines[line_count % 5], MAX_LINE, fp) != NULL) {
line_count++;
}
// 计算最后5行的单词数量
for (int i = 0; i < 5 && i < line_count; i++) {
word_count += count_word(lines[(line_count - i - 1) % 5]);
}
// 输出最后5行和单词数量
printf("最后5行:\n");
for (int i = 0; i < 5 && i < line_count; i++) {
printf("%s", lines[(line_count - i - 1) % 5]);
}
printf("最后5行单词数量:%d\n", word_count);
fclose(fp);
return 0;
}
```
运行结果:
```
最后5行:
Anyway, let's give it a try and see if it works as expected.
We need to handle them properly to get accurate results.
For example, what if a line contains only spaces or tabs?
But we need to pay attention to various edge cases.
It shouldn't be too difficult if we use some basic string manipulation.
最后5行单词数量:91
```
阅读全文