Search code examples
cstringfilefseek

How to offset in fseek from current position


I somehow cannot ofset from SEEK_CUR:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE * fp = fopen("txt", "w+b");
    if(!fp)
        return 1;
    
    fprintf(fp, "20");
    fseek(fp, 1, SEEK_CUR);
    fprintf(fp, "19");

    long size = ftell(fp) + 1;
    rewind(fp);
    char * buf = malloc(size+1);
    buf = memset(buf, 0, size+1); //should I really do this? becuase, after the "20" there will be \0 so I won't see the rest (` 19`)
    fread(buf, sizeof(char), size, fp);
    printf("%s\n",buf);

}

output:

20

but should be 20 19, which I cannot fread() from that file, why?


Solution

  • So you write "20" to the file, then skip one byte/character ahead in the file, then write "19" to the file. The skipped character needs to be written as some value... and that value is \0.

    So you read "20\019" from the file into a buf initialized to seven \0 bytes by the memset call. buf now contains "20\019\0\0".

    printf("%s\n", buf) prints buf as a NUL terminated string, i.e. until the first NUL byte appears. That NUL byte comes immediately after the "20", so it only prints "20".

    If you were to hexdump the buffer with a hexdump function (to be written as an exercise)

    hexdump(buf, size);
    

    it would print something like

    0000  32 30 00 31 39 00      -                     20.19.