从顺序文件中选择性地打印输出行

时间:2012-11-21 00:41:02

标签: c file text-files

我可以让我的程序打印出我的文本文件,但是如何让它打印出特定的行?就像是在几行中有相同的东西,我想在运行程序时打印它们?

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

2 个答案:

答案 0 :(得分:1)

基本上你需要做的是:

  1. 在变量line中存储一个插槽(按照您所说的44个字符)。
  2. 使用strstr lib中的string.h函数查找字符串line所在的字符串"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 );
    }
    

答案 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;
}