yuviuv200
yuviuv200

Reputation: 68

How to read only certain parts of text file using fscanf() in C

I have to read filenames from a text file with the following format:

#start Section-1

    file1 file2 file3
file4

#end Section-1

#start Section-2

    some random text

#end Section-2

Is there any way I can use the fscanf() function to read just the filenames and ignore everything else?

Upvotes: 0

Views: 676

Answers (1)

BlueLightning42
BlueLightning42

Reputation: 354

assuming you only care about the filenames after Section-1 and to #end you could skip to section-1 and then read until #end before closing the file...

example code

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

int main(void) {
    FILE * fp;
    fp = fopen("example.txt", "r");
    char temp[20];
    //skip to Section-1
    do{
        fscanf(fp, "%s", temp);
    }while(strcmp (temp, "Section-1"));
    //print out all filenames
    for(;;){
        fscanf(fp, "%s", temp);
        if(strcmp(temp, "#end") == 0) break;
        //do whatever you want with the filenames instead of print them
        printf("%s ", temp); //prints file1 file2 file3 file4
    }
    //close file
    fclose(fp);
  return 0;
}

this is making a lot of assumptions based on your question like that you don't care about stuff after the point named "section-1"

Its also just an example and very brittle if your actual name isn't section 1 it would have to be changed slightly. if filenames are larger than 20 that would need to change. this sample code also doesn't include any error checking or handling.

Upvotes: 1

Related Questions