繁体   English   中英

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

[英]Storing words from text file into char array using feof

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

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

有很多,确切地说是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的功能,但找不到太多东西

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

  • 将整个文本文件转储到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. 而不是检查feof() ,它会告诉您文件结尾是否在先前的输入操作中发生,而应检查fscanf()的结果

  2. 读取带有"%s" “单词”,并限制要读取的最大char数。

     char buf[100]; fscanf(in_file,"%99s",buf); 

放在一起:

    #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个数组。 然后在打印时,跳过空白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM