user13243126
user13243126

Reputation:

Is there a way i can prevent EOF in C?

So I'm scanning strings from a file and comparing them with the string from a stack. If i scan all the string from the file and don't find the one from the stack i want to rewind the file, pop the string from the stack and continue unless the stack is empty.

char buffer[ENOUGH];
while(fscanf(stream, "%s", buffer) != EOF)
{
    if(strcmp(buffer, tos->string) == 0)
    {
        pop(&tos);
        //do something with the string
    }
    // here i would need something to stop the EOF
}

I have a file like this:

02.01.2021 8:45 8:57 9:45
03.01.2021 15:40 16:30
05.01.2021 07:30 08:30

And stack contains:

01.01.2021 <- TOS
02.01.2021
03.01.2021
04.01.2021

So i need to find 01.01.2021 in file and if not there remove it from stack.

Upvotes: 0

Views: 620

Answers (3)

chqrlie
chqrlie

Reputation: 145297

To avoid reading the stream till the end of file, just break from the loop. Also note that you should compare the return value of fscanf() to 1 to detect all cases of failure. fscanf() will not return 0 for the %s or %c conversions, but would do so for other specifiers in case of a match failure that does not happen at end of file. Also pass a maximum number of characters to avoid undefined behavior on long input strings.

    char buffer[100];
    while (fscanf(stream, "%99s", buffer) == 1) {
        if (strcmp(buffer, tos->string) == 0) {
            pop(&tos);
            //do something with the string
            break;   // break from the loop.
        }
    }
    rewind(stream);

Upvotes: 1

XO56
XO56

Reputation: 330

You can use a method,

#include <stdio.h>

void compare(){
    char buffer[ENOUGH];

    while(fscanf(stream, "%s", buffer) != EOF){
        if(strcmp(buffer, tos->string) == 0){
            //do something
        }
    }
}

int main(void) {
    while(!stactIsEmpty()){
        pop();
        compare();
    }
    return 0;
}

This code is not tested. I hope you'll get the idea.

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50902

Probably something like this:

while (1)
{
  if (fscanf(stream, "%s", buffer) != EOF)
  {
    if (strcmp(buffer, tos->string) == 0)
    {
      if (stack is empty)
        break;

      pop(&tos);
      //do something with the string
    }
  }
  else
  {
    fseek(stream, 0, SEEK_SET);
  }
}

This is untested code, but you should get the idea.

But there is something flawed in your algorithm anyway: what happens if strcmp(buffer, tos->string) is never true?

Upvotes: 0

Related Questions