diff --git a/inc/stdio.h b/inc/stdio.h index 7a1682f..4560745 100644 --- a/inc/stdio.h +++ b/inc/stdio.h @@ -8,7 +8,7 @@ typedef struct FILE FILE; typedef struct { - int64_t pos; + int64_t offset; mbstate_t mbstate; } fpos_t; diff --git a/src/_win/stdio.c b/src/_win/stdio.c index b599dd4..4739233 100644 --- a/src/_win/stdio.c +++ b/src/_win/stdio.c @@ -413,6 +413,41 @@ cum: return 0; } +int fgetpos(FILE *restrict stream, fpos_t *restrict pos) { + LONG pos_hi = 0; + DWORD pos_lo = SetFilePointer(stream->handle, 0, &pos_hi, FILE_CURRENT); + if(pos_lo == INVALID_SET_FILE_POINTER) { + return 1; + } + int64_t offset = ((int64_t)pos_hi << 32) | (int64_t)pos_lo; + pos->offset = offset; + pos->mbstate = stream->mbstate; + return 0; +} + +int fseek(FILE *stream, long int offset, int whence) { + return 0; +} + +int fsetpos(FILE *stream, const fpos_t *pos) { + LONG pos_hi = pos->offset >> 32; + LONG pos_lo = (LONG)(pos->offset & 0xffffffff); + DWORD status = SetFilePointer(stream->handle, pos_lo, &pos_hi, FILE_BEGIN); + if(status == INVALID_SET_FILE_POINTER) { + return 1; + } + stream->mbstate = pos->mbstate; + return 0; +} + +long int ftell(FILE *stream) { + return 0; +} + +void rewind(FILE *stream) { + +} + int getchar(void) { return fgetc(stdin); } diff --git a/test.bin b/test.bin new file mode 100644 index 0000000..387fd58 --- /dev/null +++ b/test.bin @@ -0,0 +1 @@ +abdc \ No newline at end of file diff --git a/test/test_io.c b/test/test_io.c index b72d908..cf4d0a1 100644 --- a/test/test_io.c +++ b/test/test_io.c @@ -1,16 +1,30 @@ #include #include - +#include int main(void) { - puts("stdout is printed to console"); - if (freopen("redir.txt", "w", stdout) == NULL) - { - perror("freopen() failed"); - return EXIT_FAILURE; - } - puts("stdout is redirected to a file"); // this is written to redir.txt - fclose(stdout); - return EXIT_SUCCESS; + // prepare a file holding 4 values of type char + enum {SIZE = 4}; + FILE* fp = fopen("test.bin", "wb"); + assert(fp); + fputc('a', fp); + fputc('b', fp); + fputc('d', fp); + fputc('c', fp); + fclose(fp); + + // demo using fsetpos to return to the beginning of a file + fp = fopen("test.bin", "rb"); + fpos_t pos; + int c = fgetc(fp); + printf("First value in the file: %c\n", c); + fgetpos(fp, &pos); + c = fgetc(fp); + printf("Second value in the file: %c\n", c); + fsetpos(fp,&pos); + c = fgetc(fp); + printf("Second value in the file again: %c\n", c); + fclose(fp); + return 0; }