fgetpos/fsetpos

This commit is contained in:
bumbread 2022-07-28 17:57:44 +11:00
parent 4d9ca53495
commit e58cf8d645
4 changed files with 61 additions and 11 deletions

View File

@ -8,7 +8,7 @@
typedef struct FILE FILE; typedef struct FILE FILE;
typedef struct { typedef struct {
int64_t pos; int64_t offset;
mbstate_t mbstate; mbstate_t mbstate;
} fpos_t; } fpos_t;

View File

@ -413,6 +413,41 @@ cum:
return 0; 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) { int getchar(void) {
return fgetc(stdin); return fgetc(stdin);
} }

1
test.bin Normal file
View File

@ -0,0 +1 @@
abdc

View File

@ -1,16 +1,30 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <assert.h>
int main(void) int main(void)
{ {
puts("stdout is printed to console"); // prepare a file holding 4 values of type char
if (freopen("redir.txt", "w", stdout) == NULL) enum {SIZE = 4};
{ FILE* fp = fopen("test.bin", "wb");
perror("freopen() failed"); assert(fp);
return EXIT_FAILURE; fputc('a', fp);
} fputc('b', fp);
puts("stdout is redirected to a file"); // this is written to redir.txt fputc('d', fp);
fclose(stdout); fputc('c', fp);
return EXIT_SUCCESS; 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;
} }