2011-12-27 2 views
2

일반 C로 1 차원 배열로 텍스트 파일을 읽는 방법이 있습니까? 여기 내가 시도한 것 (행맨을 쓰고있다) :일반 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; 
} 

무엇이 잘못 되었나요?

+1

Word_array는 char이 아닌 char *의 배열이어야합니다. 버퍼를 동적으로 할당해야합니다 (단일 버퍼가 각 fgets에 겹쳐 쓰여지며 word_array 할당이 모두 동일합니다.) C 샘플 텍스트 처리를 찾아야합니다. – mpez0

답변

3

는 몇 가지 변경 시도를;

우선; 당신은 하나의 숯을 저장하고 있습니다. word_array[i] = *buffer;은 word_array의 각 단일 문자 슬롯에 단일 문자 (줄의 첫 번째 줄 또는 버퍼에있는)를 복사하는 것을 의미합니다.

둘째, 배열에 80K 문자가 아니라 80K 문자가 저장됩니다. 그것이 당신의 사전 파일의 길이라고 가정하면, 그 루프를 사용하여 거기에 모두 들어 맞출 수는 없습니다.

사전 파일에 80,368 단어가 있다고 가정합니다. 즉

당신이 어떤 이유로, 당신이 중 하나를해야 할 것이다, 의도적으로 1 차원 배열을 원한다면 ...하지만 내 워크 스테이션에 /usr/share/dict/words보다 약 40 만 단어 덜하지만 교수형 집행을위한 합리적인 크기 같은 소리 세 가지 각 리튬의 시작 인덱스와 병렬 배열을 만들

char word_array[80368 * 80]; 

memcpy (&(word_array[80 * i]), buffer, 80); 
  • :

    • 는 메인 프레임에 척, 모든 단어에 대해 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); 
          } 
      
    • 스위치. 당신은 최대 크기로 추측하거나 읽는 동안 RAM을 많이 낭비 할 필요가 그렇지 않은 경우로

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

    나는 후자를 권 해드립니다. (평균 단어 길이가 영어로, 약 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)); 
    

    죄송합니다,이는 서둘러 게시, 그래서 위의 테스트하지 않았습니다. 경고.

  • 3

    이 부분은 잘못이다 : 크기 (81) 변경에가 당신은 buffer에서 80,368 문자를 복사

    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; 
        } 
    } 
    

    :

    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]; 
        } 
    } 
    
    +0

    fyi, 1 행에 세미콜론이 누락되었습니다 .-) –

    +0

    word_array [i ++] = '\ 0'; –

    +0

    그 행은 무엇을합니까? –