2013-11-09 46 views
0

在一段時間內沒有做過任何C編程,但我有以下輸出字符串,但我想把它放入一個數組中操縱(在代碼中的---------註釋中)。我想我需要聲明數組的大小,但需要處理一個可變的數量。正在考慮做類似system('wc -l filename')的事情,但這聽起來真的很糟糕。必須有更好的方式:如何從輸入文件在C中創建一個動態的字符串數組

#include <stdio.h> 

int main() 
{ 
    char *inname = "test.txt"; 
    FILE *infile; 
    char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */ 
    char line_number; 

    infile = fopen(inname, "r"); 
    if (!infile) { 
     printf("Couldn't open file %s for reading.\n", inname); 
     return 0; 
    } 
    printf("Opened file %s for reading.\n", inname); 

    line_number = 0; 
    while (fgets(line_buffer, sizeof(line_buffer), infile)) { 
     ++line_number; 
     /* note that the newline is in the buffer */ 
     // --------------------- 
     // would like to put into an array of strings here rather than just printf'ing out out 

     printf("%4d: %s", line_number, line_buffer); 
    } 
    printf("\nTotal number of lines = %d\n", line_number); 
    return 0; 
} 

回答

2

首先:

char *inname = "test.txt"; 

應該

const char *inname = "test.txt"; 

然後,你要分配足夠大來存儲所有的線的陣列。由於您事先並不知道行數,因此可以使用指數存儲擴展:在數組耗盡時數組的大小加倍。

示例代碼(檢查省略清晰的錯誤,不要把它複製,粘貼到產品代碼):

size_t n = 0; 
size_t alloc_size = 4; 
char buffer[LINE_MAX]; 

char **arr = malloc(alloc_size * sizeof arr[0]); 

while (fgets(buffer, sizeof buffer, fp) != NULL) { 
    if (++n > alloc_size) { 
     alloc_size *= 2; 
     arr = realloc(arr, alloc_size * sizeof arr[0]); // don't do this 
    } 

    arr[n - 1] = strdup(buffer); 
} 
1

不幸的是,C中沒有動態數組(如果你像載體在思考的東西C++)。 您可以使用列表,並且每次您從文件讀取行時,都會在列表末尾附加新列表條目。

自C99以來還有一個「動態」數組叫做VLA(可變長度數組)。您可以聲明具有動態大小的數組(或在程序運行時已知的數組),但這不會幫助您解決問題,因爲每次都需要聲明尺寸大於前一個的新數組並將舊內容複製到新的數組中 - 這將是非常低效的。

因此,總結可能很難找到比列表更好的東西。

1

你可以瀏覽整個文件(如果文件很大,文件會很慢)並計算每個「新行」。然後用此計數大小創建一個數組,然後倒回文件並在每行中讀取。

製造商

相關問題