首页 > 解决方案 > C程序读取文件并打印数组中提到的所有行

问题描述

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)的数组。我只想打印这两行。(数组大小是根据用户输入的数字而动态变化的)。

谢谢

标签: c

解决方案


如果您的行号数组按升序排序,您可以通过如下修改代码来实现:

int lineNumbers[] = {1, 3, 5, 7, 9};
size_t numElements = sizeof(lineNumbers)/sizeof(lineNumbers[0]);
size_t currentIndex = 0;
...
while ( fgets ( line, sizeof line, file ) != NULL ) {/* read a line */
    i++;
    if (i  == lineNumbers[currentIndex]) {
        fputs ( line, stdout ); /* write the line */
        if (++currentIndex == numElements) {
            break;
        }
    }
}

这使您可以确定是否i等于下一个所需的行,而无需重复遍历数组。


推荐阅读