Home > other >  Rounding File size up to the next multiple of 16 in C
Rounding File size up to the next multiple of 16 in C

Time:08-07

So, I want a way to check if file size is a multiple of 16 and if not I want to round up the file size to the next multiple of 16 and pad it with the null byte '\x00'.

    FILE *input_stream = fopen(filename, "rb ");
    if (input_stream == NULL) {
        perror(filename);
        return;
    } 

    struct stat s;
    stat(filename, &s);
    if (s.st_size % 16 != 0) {
        fseek(input_stream, 0, SEEK_END);
        // not sure what to do after here
    }

CodePudding user response:

Why open the file before determining its size?

And, when you want to 'append' (write) to the file, you need different flags...

void chngSize( char *fName ) {
    struct stat s;

    stat( fName, &s );
    if( s.st_size & 0xF == 0 )
        return;

    char buf[16];
    memset( buf, 0, sizeof buf );

    FILE *fp = fopen( fName, "ab ");
    fseek( fp, 0, SEEK_END );
    fwrite( buf, sizeof buf[0], 16 - (s.st_size & 0xF), fp );
    fclose( fp );
}

I'll leave it to you to check return values...

  • Related