【问题标题】:C program to read a file and print all the lines that are mentioned in an arrayC程序读取文件并打印数组中提到的所有行
【发布时间】: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);——例如。你有数组溢出问题(size1,所以lineSeekArray[1] 写入越界——我使用MAX 表示数组中的条目数)。
  • 感谢您的快速响应,我想这样做。在 while 循环中使用这个 for 循环可能效率很低。有没有更好的解决方案?
  • 你量过吗?您可以安排在匹配时从数组中删除条目,这将提高性能,但如果您在实现基础方面遇到问题,那么担心性能是“过早优化”,这是 C 代码中许多邪恶的根源。
  • @JonathanLeffler 我同意你的观点,但我是 C 新手。

标签: c


【解决方案1】:

如果您的行号数组按升序排序,您可以通过如下修改代码来做到这一点:

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 是否等于下一个所需的行,而无需重复遍历数组。

【讨论】:

  • 非常感谢。这是我一直在寻找的解决方案。
【解决方案2】:

如果您确保对lineSeekArray 进行排序,使其值按升序排列,那么您可以只使用从0 到lineSeekArray 中的最大值的单个循环。现在您将只尝试读取所需的行数。您还可以避免遍历lineSeekArray

不过,您无法避免必须从文本文件的开头读取每一行。如果您以二进制格式存储它,您将具有随机访问能力。那是因为你可以只计算每一行的起始位置并直接读取它。

Initialising j = 0. 
for(i = 0; i < size; ++i){ 
    1. Attempt to read line from file and exit loop on failure.
    2. If i == lineSeekArray[j] --> print line, increment j, exit loop if j >= size
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多