使用feof将文本文件中的单词存储到char数组中

时间:2015-12-02 22:37:07

标签: c arrays text storage

所以我有一个像这样的文本文件:

零三二一五零零五七..等等

并且有很多,确切地说是9054个单词

我的想法是创建一个包含9054个空格的char数组并存储它,这是我到目前为止所做的:

#include <stdio.h>

int main(void)
{
char tmp;
int i = 0;
int j = 0;
char array[44000];

FILE *in_file;

in_file = fopen("in.txt", "r");

// Read file in to array
while (!feof(in_file))
{
      fscanf(in_file,"%c",&tmp);
      array[i] = tmp;
      i++;
}

// Display array
while (j<i)
{
      printf("%c",array[j]);
      j++;
}


fclose(in_file);

while(1);
return 0;
}

问题是我不知道如何存储单词,因为我已经完成了将每个字符存储到数组中所以它变成了一个大约44000的数组。我怎样才能使数组保持单词呢?

此外,我不知道feof函数的作用,尤其是行

while (!feof(in_file))

这条线究竟意味着什么?对不起,我还处在学习C的宝宝阶段,我试着查看feof的功能,但没有太多可以找到

2 个答案:

答案 0 :(得分:0)

通常您可以使用以下步骤:

  • 将整个文本文件转储到char缓冲区。
  • 使用strtok将char缓冲区拆分为多个标记或单词。
  • 使用指向char的指针数组来存储单个单词。

沿着这条线的东西会做。请注意,我使用您的问题标题作为文本文件。您需要适当地替换20

    int main ()
    {
        FILE *in_file;
        in_file = fopen("in.txt", "r");
        fseek( in_file, 0, SEEK_END );
        long fsize = ftell( in_file );
        fseek( in_file, 0, SEEK_SET );

        char *buf = malloc( fsize + 1 );
        fread( buf, fsize, 1, in_file ); // Dump the whole file to a char buffer.
        fclose( in_file );

        char *items[20] = { NULL };
        char *pch;

        pch = strtok (buf," \t\n");
        int i = 0;
        while (pch != NULL)
        {
            items[i++] = pch;
            pch = strtok (NULL, " \t\n");
        }

        for( i = 0; i < 20; i++ )
        {
            if( items[i] != NULL )
            {
                printf( "items[%d] = %s\n", i, items[i] );
            }
        }
        return 0;
    }

输出:

items[0] = Storing
items[1] = words
items[2] = from
items[3] = textfile
items[4] = into
items[5] = char
items[6] = array
items[7] = using
items[8] = feof?

答案 1 :(得分:0)

  1. 而不是检查feof(),它会告诉您上一个输入操作中是否发生文件结尾,请检查fscanf()的结果

  2. 使用"%s"读取“字词”,并限制要读取的char的最大数量。

    char buf[100];
    fscanf(in_file,"%99s",buf);
    
  3. 把它们放在一起:

        #define WORD_SIZE_MAX 20
        #define WORD_COUNT_MAX 10000
    
        char array[WORD_COUNT_MAX][WORD_SIZE_MAX];
        unsigned word_i = 0;
    
        for (i=0; i<WORD_COUNT_MAX; i++) {
          if (fscanf(in_file,"%19s", word_list[i]) != 1) {
            break;
          }
        }
    

    另一种方法是按原样使用OP代码。将整个文件读入1个数组。然后在打印时跳过空格。

相关问题