2012-01-24 51 views
-3

數組我如何讀取到一個數組整個字,直到從被格式化像這樣的文件換行符:文字閱讀從文本文件到用C

蘋果

葡萄

bananna

我希望從文件中將每個單詞存儲爲數組中的單獨值。我怎樣才能做到這一點?

感謝所有

+6

你有什麼迄今所做? –

+0

我試過很多不同的東西,但沒有任何工作? –

+0

「直到換行」是什麼意思?換行在哪裏?在每個單詞後還是在結尾? – MetallicPriest

回答

0

可以使用fgets功能,這樣

char word[100][100]; 
int i = 0; 

while(fgets(word[i++], 80, file)) 
    ; 
0

試試這個

char *my_strchr(char * string_ptr, char find) 
{ 
    while (*string_ptr != find) { 

     /* Check for end */ 

     if (*string_ptr == '\0') 
      return (NULL);  /* not found */ 

     ++string_ptr; 
    } 
    return (string_ptr);  /* Found */ 
} 

int words_count(char * string_ptr, char find) 
{ 
    int i = 0; 
    while (*string_ptr != '\0') { 

     /* Check for end */ 

     if (*string_ptr == find) 
      ++i;  /* not found */ 

     ++string_ptr; 
    } 
    return (i+1);  /* Found */ 
} 

int main() 
{ 
    char line[80];  /* The input line */ 
    char *first_ptr; /* pointer to the first name */ 
    char *last_ptr;  /* pointer to the last name */ 
    // char words[3][80]; 
    char **words; 
    int cnt; 

    // fgets(line, sizeof(line), stdin); 
    static const char filename[] = "C:\\Diginity-Works\\LineReader\\debug\\data.txt"; 
    FILE *file = fopen (filename, "r"); 

    while (fgets (line, sizeof line, file) != NULL) // read a line 
    { 
     /* Get rid of trailing newline */ 
     line[strlen(line)-1] = '\0';   
     cnt = words_count(line, ' '); 

     // for the "first level" 
     words = (char **) malloc(cnt * sizeof *words); 

     // In the second level 
     for(int i=0;i<cnt;++i) 
      words[i]=(char*)malloc(80);// i assume that max word length is 80 


     last_ptr = line; /* last name is at beginning of line */ 
     for(int i=0; i < cnt; ++i){ 
      first_ptr = my_strchr(line, ' ');  /* Find space */ 

      /* Check for an error */ 
      if (first_ptr == NULL) { 
       strcpy(words[i], last_ptr); 
       break; 
      } 

      *first_ptr = '\0'; /* Zero out the slash */ 

      ++first_ptr;  /* Move to first character of name */ 
      strcpy(words[i], last_ptr); 
      strcpy(line, first_ptr); 
     } 

     for(int i=0; i < cnt; ++i) 
      printf("%d : %s \n", i, words[i]); 
    } 

    return (0); 
}