在一段時間內沒有做過任何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;
}