2

我可以让我的程序打印出我的文本文件,但我怎样才能让它打印出特定的行呢?就像在几行中有相同的东西并且我希望在运行程序时打印它们?

#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;
}
4

2 回答 2

1

基本上你需要做的是:

  1. 在变量中存储一个插槽line(您所说的 44 个字符)。
  2. 使用lib 中的strstr函数查找字符串存在的位置,如果不存在,则返回一个指针。string.hline"2 - 0"NULL
  3. 如果指针不是NULL,那么您可以打印该行。
  4. 这个循环将一直持续到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 );
    }
    
于 2012-11-21T02:04:55.300 回答
-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;
}
于 2012-11-21T01:02:07.800 回答