有一段时间没有做过任何 C 编程,但我有以下输出字符串,但我想将它放入一个数组中,然后我可以操作(在 --------- 的注释中代码)。我想我需要声明数组的大小,但需要处理可变数量。正在考虑做类似的事情,system('wc -l filename')
但这听起来真的很糟糕。必须是更好的方法:
#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;
}