c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <omp.h>
struct wordcount{
char word[20];
int count;
}; //定义wordcount类型
int main()
{
FILE *fp;
struct wordcount wordcount[100000];
char essay[200000], ch, temp[20]; //定义essay数组存储文章内容,ch为每次读取的字符,temp数组暂存单词
int i, j, k, len, count;
fp = fopen("word.txt", "r");
for(i=0; (ch = fgetc(fp)) != EOF; i++)
essay[i] = ch;
len = i; //获得文章长度
#pragma omp parallel for private(i)
for(i=0; i<len; i++)
{
if(isalpha(essay[i]) || essay[i]=='-') //如果是字母或短横线,将其小写化
essay[i] = tolower(essay[i]); //否则将其替换为空格,方便单词的分割
else essay[i] = ' ';
}
k = 0;
#pragma omp parallel for private(i,j,k) shared(wordcount, essay, count)
for(i=0; i<100000 && k<len; i++)
{
for(j=0; j<20 && essay[k]!=' ' && k<len; j++, k++)
wordcount[i].word[j] = essay[k];
k++; //跳过下一个空格
}
count = i;
#pragma omp parallel for private(i,j,k) shared(wordcount, count)
for(i=0; i<count; i++)
wordcount[i].count = 0; //将所有单词出现次数初始化为0
#pragma omp parallel for private(i,j,found) shared(wordcount, count)
for(i=0; i<count; i++)
{
int found = 0;
for(j=0; j<i; j++)
{
if(strcmp(wordcount[i].word, wordcount[j].word)==0) //判断是否找到了已经处理过的单词
{
found = 1;
break;
}
}
if(!found)
{
for(j=0; j<count; j++)
{
if(strcmp(wordcount[i].word, wordcount[j].word)==0)
wordcount[i].count++;
}
}
#pragma omp critical
printf("%s %d\n", wordcount[i].word, wordcount[i].count+1); //加1是因为之前初始化的时候给count赋值为0
}
fclose(fp); //关闭文件
return 0;
}