2014-10-31 158 views
0
#include<stdio.h> 
#include<string.h> 
#include <stdlib.h> 

#define ARRAY_MAX 100 

int main() { 

    FILE *input, *output; 
    char *token[100]; 
    char buf[100]; 
    int count = 0; 
    input = fopen("/Users/home/Desktop/test.txt", "r"); 
    output = fopen("/Users/home/Desktop/test2.txt", "w"); 

    while (fgets(buf, sizeof(buf), input) != NULL) { 
     token[count] = strtok(buf, "\n"); 
     ++count; 
    } 

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

    printf("%d\n\n" ,count); 
    return 0 ; 

} 

當我運行這段代碼我得到的輸出喜歡數組不增加正常

線3

線3

線3

而比得到像

線1

線2

線3

什麼的我做錯了嗎?

+0

請發表您的意見。 – 2014-10-31 16:53:10

+0

'token [count] = strtok(buf,「\ n」);'不會複製「string」--token。 – alk 2014-10-31 16:55:05

+0

當輸入包含多於100行時會發生什麼? – user3629249 2014-11-01 04:51:46

回答

2

strtok()每次都在同一個buf上運行,所以每次都會返回相同的地址。當循環完成時,最後讀取的值位於緩衝區中,所以這就是打印的內容。

要保存複製線

while (fgets(buf, sizeof(buf), input) != NULL) { 
    token[count] = strdup(strtok(buf, "\n")); 
    ++count; 
} 
1

分配

token[count] = ... 

僅僅把緩衝區中的指針的地址。然後重新使用相同的緩衝區,並將相同的地址複製到數組的下一個元素中。什麼,你需要做的是,因爲它是讀取每個新行分配內存和緩衝的複製內容到新分配的內存:

token[count] = malloc(strlen(buf) + 1); // +1 for trailing 0 
strcpy(token[count], buf);