c语言实现统计文件当中的单词数
时间: 2024-10-18 15:08:12 浏览: 27
在C语言中,要统计一个文本文件中的单词数,可以按照以下步骤操作:
1. 打开文件:首先需要使用`fopen()`函数打开文件,检查是否成功并获取文件指针。
```c
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
printf("Failed to open file.\n");
return;
}
```
2. 读取文件内容:逐行读取文件,可以使用`fgets()`函数,并分割每一行的内容为单词数组。
```c
char line[100];
int word_count = 0;
while (fgets(line, sizeof(line), file)) {
// 对每一行进行处理
}
```
3. 分割字符串成单词:遍历每一行,使用`strtok()`函数将每个单词分隔出来,然后递增计数器。注意要先初始化`strtok()`以便后续使用,通常是将空字符`'\0'`传递。
```c
char *token = strtok(line, " \t\n"); // 分割符可以包括空格、制表符和换行符
while (token != NULL) {
word_count++;
token = strtok(NULL, " \t\n"); // 使用NULL作为参数继续分割下一个单词
}
```
4. 关闭文件:完成后记得关闭文件,释放资源。
```c
fclose(file);
```
5. 输出结果:最后打印出单词总数。
```c
printf("Total words in the file: %d\n", word_count);
```
完整的示例代码可能如下所示:
```c
#include <stdio.h>
#include <string.h>
int main() {
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
printf("Failed to open file.\n");
return 1;
}
char line[100];
int word_count = 0;
while (fgets(line, sizeof(line), file)) {
char *token = strtok(line, " \t\n");
while (token != NULL) {
word_count++;
token = strtok(NULL, " \t\n");
}
}
fclose(file);
printf("Total words in the file: %d\n", word_count);
return 0;
}
```
阅读全文
相关推荐

















