c - 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)的数组。我只想打印这两行。(数组大小是根据用户输入的数字而动态变化的)。
谢谢
解决方案
如果您的行号数组按升序排序,您可以通过如下修改代码来实现:
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
等于下一个所需的行,而无需重复遍历数组。
推荐阅读
- r-markdown - 安装 rmarkdown 包给了我非零退出状态
- methods - 我应该将什么传递给 Crystal 中的以下方法?
- java - 如何使用常量来确定要打印的 URL 中的文本行
- php - 推进:未找到“标准”类
- excel - 在每行中每隔 6 个单元格应用公式
- sql - 给定长度的 Postgres generate_series()
- java - 如何在 Java Web 应用程序(在 Tomcat 中运行)中找到热点?
- java - Flink keyBy vs RichParallelSourceFunction
- sql-server - SSIS 包仅在目录中可能丢失数据
- javascript - vuejs中如何获取组件编译后的html内容