user1731810
user1731810

Reputation: 17

Ignoring comments when reading in a file

I realise this is a very simple problem and I expected to be able to find the answer by searching on the internet but I couldn't. All I want to do is read in a file but ignore comment that start with a hash. So

FILE *fp_in;
if((fp_in = open("file_name.txt","r")) ==NULL) printf("file not opened\n");
const int bsz = 100; char buf[bsz];
fgets(buf, bsz, fp_in);  // to skip ONE line
while((fgets(buf,bsz,fp_in))! ==NULL) {
  double x,y,x;
  sscanf(buf, "%lf %lf %lf\n", &x,&y,&z);
  /////allocate values////
}

So this is OK to skip 1 line in the file but I have files with several lines proceeded by a hash key that I need to skip. Can someone help me with this, I can't seem to find the answer. Cheers

Upvotes: 0

Views: 4662

Answers (3)

Aniket Inge
Aniket Inge

Reputation: 25705

FILE *fp_in;
int chr;
if((fp_in = fopen("file_name.txt","r")) == NULL){
   printf("File not opened\n");
   exit(1);
}

while((chr = fgetc(fp_in) != EOF){
    if(chr == '#'){
       while((chr = fgetc(fp_in)) != '#' || (chr != EOF)); /*skip*/
    }
  //do the processing.
}

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183888

If the comment marker is the first character in the line,

while((fgets(buf,bsz,fp_in))! ==NULL) {
  if (buf[0] == '#') continue;
  double x,y,x;
  sscanf(buf, "%lf %lf %lf\n", &x,&y,&z);
  /////allocate values////
}

would ignore comment lines. If it's not so simple, there's no way avoiding to scan the line for comments.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477100

Add if (buf[0] == '#') continue; to the beginning of your loop.

Upvotes: 1

Related Questions