2014-05-07 68 views
0

我有以下代碼:文件需要讀取正確

int main(void) 
{ 
    int lines_allocated = 128; 
    int max_line_len = 100; 
    int lines_allocated2 = 128; 
    int max_line_len2 = 100; 

    /* Allocate lines of text */ 
    char **words = (char **)malloc(sizeof(char*)*lines_allocated); 
    if (words == NULL) 
    { 
     fprintf(stderr, "Out of memory (1).\n"); 
     exit(1); 
    } 

    FILE *fp = fopen("test1.txt", "r"); 
    if (fp == NULL) 
    { 
     fprintf(stderr, "Error opening file.\n"); 
     exit(2); 
    } 
    else 
    { 
     printf("Reading in test1.txt...\n"); 
    } 

    int i; 
    for (i = 0; 1; i++) 
    { 
     int j; 

     /* Have we gone over our line allocation? */ 
     if (i >= lines_allocated) 
     { 
      int new_size; 

      /* Double our allocation and re-allocate */ 
      new_size = lines_allocated * 2; 
      words = (char **)realloc(words, sizeof(char*)*new_size); 
      if (words == NULL) 
      { 
       fprintf(stderr, "Out of memory.\n"); 
       exit(3); 
      } 
      lines_allocated = new_size; 
     } 
     /* Allocate space for the next line */ 
     words[i] = malloc(max_line_len); 
     if (words[i] == NULL) 
     { 
      fprintf(stderr, "Out of memory (3).\n"); 
      exit(4); 
     } 
     if (fgets(words[i], max_line_len - 1, fp) == NULL) 
      break; 

     /* Get rid of CR or LF at end of line */ 
     for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--) 
      ; 
     words[i][j] = '\0'; 
    } 

    int j; 
    for (j = 0; j < i; j++) 
    { 
     printf("%s\n", words[j]); 
    } 
    return 0; 
} 

我想在一個文件中讀取和存儲的話陣列中的每一行。我的輸入文件包含:

1 345363 

0 149378 

0 234461 

0 454578 

但是,每行的最後一個數字被截斷。因此,第一個索引將打印34536,當它打印出345363.我似乎無法弄清楚什麼是錯的。

+1

僅供參考:[不要強制轉換'malloc'的返回值](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 –

+0

你最後一個字符被設置爲'\ 0' – mgamba

回答

0

的問題是在該行

for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--) 

變化j = strlen(words[i]) - 1;j = strlen(words[i]);將打印輸出正確...

+1

非常感謝你 – user3610554

0

要在行尾擺脫CR或LF的,試試這個:

char *cp; 

while((cp=strchr(words[i], '\r'))) 
    *cp='\0'; 

while((cp=strchr(words[i], '\n'))(
    *cp='\0'; 

取而代之的是:

for(j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--) 
     ; 
words[i][j] = '\0';