我可以让我的程序打印出我的文本文件,但是如何让它打印出特定的行?就像是在几行中有相同的东西,我想在运行程序时打印它们?
#include <stdio.h>
int main ( void ){
static const char filNavn[] = "test.txt";
FILE *fil = fopen( filNavn, "r" );
if ( fil != NULL ){
char line [ 256 ];
while( fgets( line, sizeof( line ), fil ) != NULL ){
fputs( line, stdout );
}
fclose( fil );
}
else{
perror( filNavn );
}
return 0;
}
答案 0 :(得分:1)
基本上你需要做的是:
line
中存储一个插槽(按照您所说的44个字符)。strstr
lib中的string.h
函数查找字符串line
所在的字符串"2 - 0"
的位置,如果不存在,则返回一个NULL
指针。NULL
,则可以打印该行。此循环将继续,直到fil
指针到达end of the file
。
if ( fil != NULL ){
/* 44 characters because you said that the data is stored in strings of 44. */
/* And I will think that you inputed the data correctly. */
char line [ 44 ];
/* While you don't reach the end of the file. */
while( !feof( fil ) ){
/* Scans the "slot" of 44 characters (You gave it that format)*/
/* starting at the position of the pointer fil and stores it in fil*/
fscanf( fil, %44s, line );
/* If the result of the internal string search (strstr) isn't null. */
/* Print the line.*/
if( strstr( line, "2 - 0" ) != NULL ){
printf( "%s\n", line )
}
/* Else keep the loop....*/
}
fclose( fil );
}
答案 1 :(得分:-1)
只需将您的条件置于读/打印循环中:
int main ( void )
{
static const char filNavn[] = "test.txt";
FILE *fil = fopen( filNavn, "r" );
if ( fil != NULL )
{
char line [ 256 ];
while( fgets( line, sizeof line, fil ) != NULL )
{
// if this line is interesting (eg, has something "the same")
fputs( line, stdout );
}
fclose( fil );
}
else
{
perror( filNavn );
}
return 0;
}