Thread: fseek not working as expected when searching in reverse

  1. #1
    C lover
    Join Date
    Oct 2007
    Location
    Virginia
    Posts
    266

    fseek not working as expected when searching in reverse

    I get garbage from the file I'm reading when I try searching in reverse. I want to go in reverse until I find the '-' character and get all characters until the next '-' but I get garbage in the resulting character string... My intention is to start searching in the middle of the file.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define BLOCK 1024
    
    void poll_file(FILE * file, char * message){
    
      int pos = 0, i = 0, c = 0;
      
      fseek(file, 0, SEEK_END);
      pos = ftell(file) / 2;
      fseek(file, pos, SEEK_SET);
    
      while((c = fgetc(file)) != '-')
        fseek(file, --pos, SEEK_SET);
    
      while((c = fgetc(file)) != '-')
        message[i++] = (char)c;
    
      message[i] = '\0';
    
    }
    
    int main(int argc, char ** argv){
    
      
      char message[BLOCK];
    
      FILE * file;
    
      if((file = fopen(argv[1], "r"))){ 
        poll_file(file, message);
        printf("Message found in image: %s\n", message);
      }
      else
        printf("Error opening file\n");
    
      return 0;
    }

  2. #2
    C lover
    Join Date
    Oct 2007
    Location
    Virginia
    Posts
    266
    Nevermind, figured it out with a little more inspection

    Code:
    
      while((c = fgetc(file)) != '-')
        fseek(file, -2, SEEK_CUR);

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Remember on Windows OS, it makes a difference whether you opened the file in Binary or Text mode.
    (Normally, but not always, binary works better.)

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. && not working as expected
    By TonyBalony in forum C Programming
    Replies: 4
    Last Post: 12-14-2011, 12:30 PM
  2. Multithreading not working as expected
    By shiroaisu in forum Windows Programming
    Replies: 5
    Last Post: 06-18-2011, 02:34 AM
  3. Program not working as expected
    By perrrson in forum C Programming
    Replies: 3
    Last Post: 10-02-2010, 01:49 PM
  4. srand() no working as expected
    By guesst in forum C++ Programming
    Replies: 2
    Last Post: 01-15-2009, 12:24 PM
  5. IntersectRect() not working as expected?
    By dxfoo in forum Windows Programming
    Replies: 1
    Last Post: 09-05-2006, 04:52 PM