【发布时间】:2023-03-03 23:52:01
【问题描述】:
const int size = 1;
int lineSeekArray[size];
lineSeekArray[0] = 0;
lineSeekArray[1] = 1;
static const char filename[] = "testfile.txt";
FILE *file = fopen ( filename, "r" );
int i =0;
if ( file != NULL )
{
char line [ 328 ]; /* or other suitable maximum line size */
while ( fgets ( line, sizeof line, file ) != NULL ) {/* read a line */
i++;
if(i == 9)
{
fputs ( line, stdout ); /* write the line */
}
}
fclose ( file );
现在我的代码打印文件的第 9 行。是否有任何有效的方法来打印数组中的行号。 基本上,如果我有两个整数(如 0 和 1)的数组。 我只想打印这两行。 (数组大小是根据用户输入的数字动态变化的)。
谢谢
【问题讨论】:
-
使用循环代替
if (i == 9)行?for (int j = 0; j < MAX; j++) if (lineSeekArray[j] == i) fputs(line, stdout);——例如。你有数组溢出问题(size是1,所以lineSeekArray[1]写入越界——我使用MAX表示数组中的条目数)。 -
感谢您的快速响应,我想这样做。在 while 循环中使用这个 for 循环可能效率很低。有没有更好的解决方案?
-
你量过吗?您可以安排在匹配时从数组中删除条目,这将提高性能,但如果您在实现基础方面遇到问题,那么担心性能是“过早优化”,这是 C 代码中许多邪恶的根源。
-
@JonathanLeffler 我同意你的观点,但我是 C 新手。
标签: c