2

I am trying to read multiples integers from a file using a loop. The problem I am facing is there's a string in between those integers. My goal is to find the last integer in the file ex:- 123 hello 1253 world So in the above case, the last integer would be 1253.

int id;
p=fopen("o.txt","r");
while(!feof(p))
{
    fscanf(p,"%d",&id);
    fseek(p,13,SEEK_CUR);
} ```

   

I used `fseek()` to jump over the string. There were 13 characters from the last digit to the beginning of the next digit.
This does not work and I ended up in an infinite loop.
Can anyone help?
Thank you
shehan chanuka
  • 71
  • 1
  • 10
  • Use `fgets` to read one line. Then use `strtok` to parse the string into tokens. Or use multiple `fscanf` format specifiers - one for each of the tokens. – kaylum Jan 25 '21 at 00:18
  • 3
    Fyi, [`while(!feof(p))` is *wrong*](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – WhozCraig Jan 25 '21 at 00:18
  • You can read char by char with ...`%c`... then try to convert on int, if convert return true then save that number into a int variable, else, discard that char and read the next one, i would recomend `strtol` for conversions from chars to ints – Paul Bob Jan 25 '21 at 00:33

1 Answers1

1

My goal is to find the last integer in the file ex:- 123 hello 1253 world So in the above case, the last integer would be 1253.

while(!feof(p)) --> Why is “while ( !feof (file) )” always wrong?

A slow solution: read the entire file. Look for integers. If the next input is not an integer, consume input as a character and toss it (test for EOF)

long long last = 0;
for (;;) {
  long long i; 
  // Try to read 1 integer
  if (fscanf(p, "%lld", &i)==1) {
    last = i;
  } else {
    // read and consume one character.
    if (fgetc(p) == EOF) break;
  }
}
printf("Last: %lld\n", last);

Other ideas, go to the end. Repeated seek back until fail, or reading forward yields an integer.

Untested idea. Not itself that efficient, but to give OP an idea.

long offset = 0;
while (fseek(p,--offset,SEEK_END) == 0) {
  long long last;
  if (fscanf(p, "%lld", &last)==1) {
    while (fseek(p, --offset, SEEK_END) == 0) {
      long long i;
      if (fscanf(p, "%lld", &i)==1) {
         last = i;
      }
    }
    printf("Last: %lld\n", last);
    break;
  }
}
    

Use of ftell(), fseek() is problematic with text files as an fseek() to any place other than the beginning or relative to a previous ftell() result is UB. Consider opening with "rb".

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256