计算文本文件中每个单词的出现次数

时间:2016-03-14 11:11:54

标签: c algorithm file data-structures hashtable

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int word_count()
{
    FILE *p;
    char ch;
    int w = 0;
    p = fopen("input.txt", "r");
    if (p == NULL)
    {
        printf("Error opening file\n");
        exit(0);
    }
    else
    {
        ch = fgetc(p);
        while (ch != EOF)
        {
            if (ch == ' ' || ch == '\n')
            {
                w++;
            }
            ch = fgetc(p);
        }
        return w;
    }
    fclose(p);
}

void main()
{
    FILE *fp1, *fp2;
    char ch;
    void *p;
    int i, n;
    w = word_count()

        fp2 = fopen("output.txt", "w");
    if (p == NULL)
    {
        printf("Error opening file\n");
        exit(0);
    }
    else
    {
        fprintf("Words\t\t occurrences\t\n);
            exit(0);
    }
    fp1 = fopen("input.txt", "r");
    if (p == NULL)
    {
        printf("Error opening file\n");
        exit(0);
    }
    else
    {
        for (i = 0; i < w; i++)
        {
            ch = fgetc(f1);
            p = &ch;
            p++;
            while (ch != EOF)
            {
                while (strcmp(ch, *p) == 0)
                {
                    n++;
                    p++;
                }
                fputc(ch, fp2);
                fputc(n, fp2);
            }
        }
        ch++;
    }
    fclose(fp1);
    fclose(fp2);
}

我的教授已经要求我编写一个可以读取文件并找到每个单词出现的代码。这是我尝试的代码,但它要求我使用比指针更好的东西,可能是哈希表并跟踪所有单词并计算它们的出现次数。 我无法选择正确的数据结构,因为我只是一个初学者,我需要帮助选择数据结构。

0 个答案:

没有答案
相关问题