简体   繁体   中英

How can I read specific lines in a file?

In a file, words like this are written:

Name 
Surname 
Age
Job
Telephone
James
Cooper
26
engineer
6545654565
Bob
Allen
22
doctor
5656555655
  ....

I want to print specific parts from these lines (for examples only names). I have tried this code but I can only print 1 line I want. (I print only James but I want to print all names: James, Bob,...).

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{  
    int lineNumber;   
    static const char filename[] = "hayat.txt";

    for(lineNumber=5;lineNumber<20;lineNumber+5);    

    FILE *file = fopen(filename, "r");
    int count = 0;

    if ( file != NULL )
    {   
        char line[256]; 
        while (fgets(line, sizeof line, file) != NULL) 
        {   
            if (count == lineNumber)
            {                   
                printf("\n  %s ", line);
                fclose(file);

                return 0;  
            }   
            else
            {   
                count++;
            }               
        }   
        fclose(file);
    }  

    return 0;  
}

How can I do this?

I tried to make it work writing the code the most similar to the code in the question. This might not be the optimal solution but should work.

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

#define TAMLINE 256

int main(void){
    int lineNumber, count=0;
    static const char filename[] = "hayat.txt";
    FILE *file = fopen(filename, "r");
    if ( file != NULL ){
        char line[TAMLINE];
        /* //use this if you want to skip first 5 lines
        for(int i=0;i<5;i++){
            fgets(line, TAMLINE, file)
        }
        */
        while (fgets(line, TAMLINE, file) != NULL){
            count ++;
            //only print 1st line, 6th line 11 line.. ie lines with names
            if (count%5 == 1){
                printf("%s", line);
            }
        }
    fclose(file);
    }
    return 0;
}

You only print once because that's exactly what are telling the programm to do

if linenumber == count ... print 

else count++ 

will always print only one line.

As for how to print difference categories, you either find similarities ( like some Objects and all names start with a capital letter and no number) or you specify them in an array - which probably would not be what you would like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM