0

I am using fgets() to scan a file as follows:

char buf[50];
if (fgets(buf, 50, fp) == NULL) {
  printf("Error in file parsing.\n");
  exit(1);
}
char *p;
p = buf;

p points to buffer and I am using it to iterate through the scanned string. fgets() has size 50, but it does indeed add a null terminator at the end of the scanned string.

My while loop looked as follows:

while (*p != '\0')

This worked when my text file had: 1 + 23. When the text file contained 1 + 23 - 5, it hits an infinite loop. Why is this happening?

I also tried checking for \n which also failed. At the end, I used strlen and had a for loop run according to strlen but that wasn't accurate.

Any suggestions on what my while loop should look like?

darksky
  • 20,411
  • 61
  • 165
  • 254
  • 4
    Show more code. You might be forgetting to increment `p` , or have an error elsewhere. Checking for '\0' is the proper way. strlen() very "accurate", so that too indicates an error elsewhere. – nos Jul 17 '12 at 09:19
  • 1
    Besides forgetting to increment as noted by @nos, you might also increment `p` one time to many and skip over the terminating `'\0'`. – Some programmer dude Jul 17 '12 at 09:21
  • Really would like to see the whole loop. Try and leave out the irrelevant bits, while keeping the stuff that reproduces the problem. – ArjunShankar Jul 17 '12 at 09:29
  • I do increment `p`. I think the issue is that I am incrementing over the `\0`. I guess I will need to check wherever I increment `p` multiple times, if an `\0` is found, just break out of the loop. @JoachimPileborg you got it right. – darksky Jul 17 '12 at 13:38

1 Answers1

1

Why not to iterate as follows:

int i, buflen;
buflen = strlen(buf);
for(i=0; i<buflen; i++) {
   // your code on buf[i]
}
A_nto2
  • 1,106
  • 7
  • 16
  • 2
    [Some compilers may call `strlen` each time](http://stackoverflow.com/q/2049480/274261). Better to call it outside the loop. – ArjunShankar Jul 17 '12 at 09:27
  • That's how I did it. See comments above please. – darksky Jul 17 '12 at 13:38
  • @Darksky: It's more common to iterate over a string as I suggested to you. – A_nto2 Jul 17 '12 at 13:56
  • @A_nto2 I've tried that but it failed as well. That is because I am reading characters and integers from the string. I am reading a character using `*p` as normally I would do and then incrementing `p`. As for the integers, I am using `sscanf` and then I am calculating how many digits the number has using log, and incrementing `p` by that (in order to step to the next character after the integer). Using `buf[i]`, I will still need to use `sscanf` and calculate the length of a digit to skip to the next `i`. So that would still pose the same problem, and my loop is bounded to use a i+1 increment – darksky Jul 18 '12 at 06:49
  • @Darksky You should show the full code which gave the issue, actually. – A_nto2 Jul 18 '12 at 07:01