fseek() broken under Windows?

This is a discussion on fseek() broken under Windows? within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> int main() { FILE* fp = fopen("main.c", "r"); fputc(fgetc(fp), stdout); fseek(fp, -1, SEEK_CUR); fputc(fgetc(fp), stdout); return 0; ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    China
    Posts
    74

    Angry fseek() broken under Windows?

    Code:
    #include <stdio.h>
    
    int main()
    {
        FILE* fp = fopen("main.c", "r");
        fputc(fgetc(fp), stdout);
        fseek(fp, -1, SEEK_CUR);
        fputc(fgetc(fp), stdout);
        return 0;
    }
    Under linux, the two fgetc() will return the same character "#". But under Windows the second fgetc() returns EOF. Why is that happen?

    BTW, if I change the code to fseek(fp, 0, SEEK_CUR), Linux returns two different characters "#" and "i" while windows returns two "#".

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,448
    If you read the standard, you will find that "for a binary stream, the new position, measured in characters from the beginning of the
    file, is obtained by adding offset to the position specified by whence", and that "for a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET".

    You did not specify binary mode, yet you are using the file stream as if it were a binary stream. Thus, write:
    Code:
    FILE* fp = fopen("main.c", "rb");
    and check if it works in both cases.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2010
    Location
    China
    Posts
    74
    FILE* fp = fopen("main.c", "rb");
    That works both on windows and linux. Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Windows 98/2000 programming in Windows XP
    By Bill83 in forum Windows Programming
    Replies: 3
    Last Post: 07-22-2005, 02:16 PM
  2. Dialog Box Problems
    By Morgul in forum Windows Programming
    Replies: 21
    Last Post: 05-31-2005, 05:48 PM
  3. dual boot Win XP, win 2000
    By Micko in forum Tech Board
    Replies: 6
    Last Post: 05-30-2005, 02:55 PM
  4. SDL and Windows
    By nickname_changed in forum Windows Programming
    Replies: 14
    Last Post: 10-24-2003, 12:19 AM
  5. IE 6 status bar
    By DavidP in forum Tech Board
    Replies: 15
    Last Post: 10-23-2002, 05:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21