Thread: Tailing a file, fseek help

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    25

    Tailing a file, fseek help

    Having some troubles. The idea is that if the file size is greater than 100 bytes, then the file is sought to the 100th to last byte. Then the file is printed to the screen. I'm getting a segfault at the fseek for >100 files, and a segfault at the getc. GDB isn't really helping explain why (for my knowledge base). If I call my list_file(Filename) function similar files (it cats them to stdout), the getc operates normally.


    EDIT: Problem solved rookie mistake.

    Here's my code:

    Code:
    void tail_file(char* filename)
    {
      //Check if size is smaller than 100 bytes
      struct stat file_stats;
      stat(filename, &file_stats);
      int size = file_stats.st_size;
      FILE *f;
      if((fopen(filename, "r")) == NULL)
      {
        perror("The function 'fopen' failed");
        return;
      }
      printf("opened the file!\n");
      if(size > 100)
      {
        printf("size was greater than 100 \n");
        if((fseek(f, -100, SEEK_END)) != 0)  //ERROR
          perror("The function 'fseek' failed");
      }
      char c;
      while( (c = fgetc(f)) != EOF) //error in here
        putchar(c); 
      fclose(f);
    }
    example of gdb output:

    Program received signal SIGSEGV, Segmentation fault.
    0xb7ea318d in getc () from /lib/tls/i686/cmov/libc.so.6
    (gdb) where
    #0 0xb7ea318d in getc () from /lib/tls/i686/cmov/libc.so.6
    #1 0x0804898a in tail_file (filename=0xbfdbac1a "tee") at functions.c:132
    #2 0x080489c1 in main (argc=Cannot access memory at address 0x11
    ) at functions.c:138

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    The problem is that you aren't assigning the handle returned by fopen to the file variable f.

    Code:
      FILE *f;
      if((fopen(filename, "r")) == NULL)
    Thus when you call fseek() it's working from an undefined handle.

    Try this...
    Code:
    FILE *f = fopen(filename,"r");
    if (! f)
      { printf("Could not open file");
         exit(1); }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Leak in AppWizard-Generated Code
    By jrohde in forum Windows Programming
    Replies: 4
    Last Post: 05-19-2010, 04:24 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM