Thread: fseek() broken under Windows?

  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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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