This one comes from file-handling.

Say , i have a file of 95,000 lines. I have to analyse only those lines which start with a semi-colon.
So my logic would be like, "Read first character of the line, if it IS a semi-colon, process it, otherwise jump to the next line."

My question is :
Is there any in-built function or logic, that takes me to the next line in the file(that is vertically below) without having to scan the other characters in the same line. That is, i want something that is the equivalent of \n(carriage return + line feed)

At the moment, what i am doing is, storing the entire line in a buffer, and then seeing the first character of the buffer. The code would be something like

fgets(buffer, 100, file_pointer);
if(*buffer == ';')
{
 /* process data */
}

else
{
 /* again do an fgets and repeat the process */
 /* I have not put the whole thing in a loop while posting this, for the sake of simplicity */
}

This logic , OK, helps to process on the basis of the first character, but then, i am again saving the whole thing in a buffer, which is basically reading the entire line. (Atleast i am making fgets read char-by-char)

Please give me your suggestions

You are doing the right thing already. Anything else is just more complicated, time consuming, and obfuscated.

Just because you read a line, doesn't mean you have to scan the characters.

I really like the way you're thinking on this! Well done.

fgets() is what you want, but you're quite right that fgets() has to go char by char (at a very low and fast level), to find the end of each row of text.

It is NOT the same thing as scanning, like getchar(), because there is no conversion going on, but still, it is a char by char check for that newline char. There's nothing you can do about that. Any other function you could use, would still have to make that check to see if the next char was a semi-colon.

Having fgets() put each line of text into the same buffer array is the right way to go, the address of the buffer is kept in cache, thus accessed very quickly. You should be using a while or for loop for this, something like:

while((fgets(arrayName, 100, filePointer)) != NULL) {
   if(*arrayName == ';') {
      handle that here. Array already has the text you need
      to work with.
   }
}

No "else" is needed, because you're using the loop logic, itself. It's concise, clean and fast.

Edited 5 Years Ago by Adak: n/a

This article has been dead for over six months. Start a new discussion instead.