将文本文件读入普通C中的数组

时间:2011-12-27 18:09:06

标签: c file gcc io stdio

有没有办法在纯C中将文本文件读入一维数组?这是我尝试过的(我正在写刽子手):

int main() {
    printf("Welcome to hangman!");

    char buffer[81];
    FILE *dictionary;
    int random_num;
    int i;
    char word_array[80368];

    srand ( time(NULL) );

    random_num = rand() % 80368 + 1;
    dictionary = fopen("dictionary.txt", "r");

    while (fgets(buffer, 80, dictionary) != NULL){
        printf(buffer); //just to make sure the code worked;
        for (i = 1; i < 80368; i++) {
            word_array[i] = *buffer;
        }
    }

    printf("%s, \n", word_array[random_num]);
    return 0;
}

这里有什么问题?

2 个答案:

答案 0 :(得分:3)

这部分错了:

while (fgets(buffer, 80, dictionary) != NULL){
    printf(buffer); //just to make sure the code worked;
    for (i = 1; i < 80368; i++) {
        word_array[i] = *buffer;
    }
}

您正在从buffer复制80368个字符,其大小为81.将其更改为:

i = 0;
while (fgets(buffer, 80, dictionary) != NULL){
    printf(buffer); //just to make sure the code worked;
    for (j = 0; j < 80; j++) {
        word_array[i++] = buffer[j];
    }
}

答案 1 :(得分:3)

尝试改变一些事情;

首先;你要存储一个字符。 word_array[i] = *buffer;表示将单个字符(缓冲区中的第一个字符)复制到word_array中的每个(和每个)单字符插槽中。

其次,你的数组将保存80K字符,而不是80K字。假设这是你的字典文件的长度,你不能在那里使用那个循环。

  

我假设您的词典文件中有80,368个单词。不过,这比我工作站上的/usr/share/dict/words少了400,000个字,但对于刽子手来说听起来像是一个合理的大小......

如果你故意想要一维数组,出于某种原因,你必须做以下三件事之一:

  • 假装你在大型机上,并为每个单词使用80个字符:

      char word_array[80368 * 80];
    
    memcpy (&(word_array[80 * i]), buffer, 80);
    
  • 创建一个并行数组,其索引指向巨大缓冲区中每行的开头

       int last_char = 0;
       char* word_start[80368];
       char word_array[80368 * 80];
       for ( … i++ ) {
           memcpy (&word_array[last_char], buffer, strlen(buffer));
           word_start[i] = last_char;
           last_char += strlen(buffer);
       }
    
  • 切换到使用指向char的指针数组,每个插槽一个字。

      char* word_array[80368];
    
      for (int i = 0; i < 80368, i++) {
           fgets (buffer, 80, dictionary);
           word_array[i] = strdup (buffer);
      }
    

我推荐后者,否则你必须猜测最大尺寸或在阅读时浪费大量RAM。 (如果你的平均单词长度大约是4-5个字符,就像英文一样,你平均每个单词浪费75个字节。)

我还建议动态分配word_array:

   int max_word = 80368;
   char** word_array = malloc (max_word * sizeof (char*));

...如果您的字典大小有所改变,它可以让您更安全地阅读:

   int i = 0;
   while (1) {
        /* If we've exceeded the preset word list size, increase it. */
        if ( i > max_word ) {
            max_word *= 1.2; /* tunable arbitrary value */
            word_array = realloc (word_array, max_word * sizeof(char*));
        }
        /* Try to read a line, and… */
        char* e = fgets (buffer, 80, dictionary);
        if (NULL == e) { /* end of file */
            /* free any unused space */
            word_array = realloc (word_array, i * sizeof(char*));
            /* exit the otherwise-infinite loop */
            break;
        } else {
            /* remove any \r and/or \n end-of-line chars */
            for (char *s = &(buffer[0]); s < &(buffer[80]); ++s) {
               if ('\r' == *s || '\n' == *s || '\0' == *s) {
                  *s = '\0'; break;
               }
            }
            /* store a copy of the word, only, and increment the counter.
             * Note that `strdup` will only copy up to the end-of-string \0,
             * so you will only allocate enough memory for actual word
             * lengths, terminal \0's, and the array of pointers itself. */
            *(word_array + i++) = strdup (buffer);
        }
    }
    /* when we reach here, word_array is guaranteed to be the right size */
    random = rand () % max_word;
    printf ("random word #%d: %s\n", random, *(word_array + random));

抱歉,这是匆忙发布的,所以我没有测试过上面的内容。注意事项。