3 /* fseek( FILE *, long offset, int )
5 This file is part of the Public Domain C Library (PDCLib).
6 Permission is granted to use, modify, and / or redistribute at will.
13 #include <_PDCLIB_glue.h>
15 int fseek( struct _PDCLIB_file_t * stream, long loffset, int whence )
17 _PDCLIB_int64_t offset = loffset;
18 if ( stream->status & _PDCLIB_FWRITE )
20 if ( _PDCLIB_flushbuffer( stream ) == EOF )
25 stream->status &= ~ _PDCLIB_EOFFLAG;
26 if ( stream->status & _PDCLIB_FRW )
28 stream->status &= ~ ( _PDCLIB_FREAD | _PDCLIB_FWRITE );
31 if ( whence == SEEK_CUR )
34 offset += _PDCLIB_ftell64( stream );
37 return ( _PDCLIB_seek( stream, offset, whence ) != EOF ) ? 0 : EOF;
43 #include <_PDCLIB_test.h>
49 TESTCASE( ( fh = tmpfile() ) != NULL );
50 TESTCASE( fwrite( teststring, 1, strlen( teststring ), fh ) == strlen( teststring ) );
51 /* General functionality */
52 TESTCASE( fseek( fh, -1, SEEK_END ) == 0 );
53 TESTCASE( (size_t)ftell( fh ) == strlen( teststring ) - 1 );
54 TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
55 TESTCASE( (size_t)ftell( fh ) == strlen( teststring ) );
56 TESTCASE( fseek( fh, 0, SEEK_SET ) == 0 );
57 TESTCASE( ftell( fh ) == 0 );
58 TESTCASE( fseek( fh, 5, SEEK_CUR ) == 0 );
59 TESTCASE( ftell( fh ) == 5 );
60 TESTCASE( fseek( fh, -3, SEEK_CUR ) == 0 );
61 TESTCASE( ftell( fh ) == 2 );
62 /* Checking behaviour around EOF */
63 TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
64 TESTCASE( ! feof( fh ) );
65 TESTCASE( fgetc( fh ) == EOF );
66 TESTCASE( feof( fh ) );
67 TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
68 TESTCASE( ! feof( fh ) );
69 /* Checking undo of ungetc() */
70 TESTCASE( fseek( fh, 0, SEEK_SET ) == 0 );
71 TESTCASE( fgetc( fh ) == teststring[0] );
72 TESTCASE( fgetc( fh ) == teststring[1] );
73 TESTCASE( fgetc( fh ) == teststring[2] );
74 TESTCASE( ftell( fh ) == 3 );
75 TESTCASE( ungetc( teststring[2], fh ) == teststring[2] );
76 TESTCASE( ftell( fh ) == 2 );
77 TESTCASE( fgetc( fh ) == teststring[2] );
78 TESTCASE( ftell( fh ) == 3 );
79 TESTCASE( ungetc( 'x', fh ) == 'x' );
80 TESTCASE( ftell( fh ) == 2 );
81 TESTCASE( fgetc( fh ) == 'x' );
82 TESTCASE( ungetc( 'x', fh ) == 'x' );
83 TESTCASE( ftell( fh ) == 2 );
84 TESTCASE( fseek( fh, 2, SEEK_SET ) == 0 );
85 TESTCASE( fgetc( fh ) == teststring[2] );
86 /* PDCLIB-7: Check that we handle the underlying file descriptor correctly
87 * in the SEEK_CUR case */
88 TESTCASE( fseek( fh, 10, SEEK_SET ) == 0 );
89 TESTCASE( ftell( fh ) == 10l );
90 TESTCASE( fseek( fh, 0, SEEK_CUR ) == 0 );
91 TESTCASE( ftell( fh ) == 10l );
92 TESTCASE( fseek( fh, 2, SEEK_CUR ) == 0 );
93 TESTCASE( ftell( fh ) == 12l );
94 TESTCASE( fseek( fh, -1, SEEK_CUR ) == 0 );
95 TESTCASE( ftell( fh ) == 11l );
96 /* Checking error handling */
97 TESTCASE( fseek( fh, -5, SEEK_SET ) == -1 );
98 TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
99 TESTCASE( fclose( fh ) == 0 );