Home > Software engineering >  Read n bytes from file and get integer value
Read n bytes from file and get integer value

Time:09-15

I'm working on a coding challenge where I have to read n bytes from an encoded file and perform some operations with them. I am trying to get the integer value of the bytes to use as a seed for srand().

I'm not sure I'm doing this properly. I am passing in 4 and file pointer to read_n_bytes() in which I am reading 4 bytes from the file and writing them to a location in memory set aside with malloc(). Then returning the malloc() address as a char pointer as seed and attempting to access the bytes with &seed.

The rest of my operation isn't working here.

Am I going about this the right way?

char* seed;

int main() {
    FILE * fp;

    fp = fopen("flag.enc", "rb");

    // extract seed from flag
    seed = read_n_bytes(4, fp);

    srand(&seed);
}

char* read_n_bytes(int b, FILE * fp) {
    char * buffer;
    buffer = malloc(b);
    fread(buffer, 1, b, fp);
    return buffer;
}

CodePudding user response:

srand() wants an integer, not a char** pointer that you are trying to give it. You would have to typecast and dereference the pointer to access the integer value, eg:

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

char* read_n_bytes(size_t b, FILE *fp);

int main() {
    FILE *fp = fopen("flag.enc", "rb");
    if (fp == NULL) {
        // error handling...
    }

    // extract seed from flag
    uint32_t *seed = (uint32_t*) read_n_bytes(sizeof(uint32_t), fp);
    if (seed == NULL) {
        // error handling...
    }

    srand(*seed);

    free(seed);
    fclose(fp);
}

char* read_n_bytes(size_t b, FILE *fp) {
    char *buffer = malloc(b);
    if (buffer) {
        if (fread(buffer, b, 1, fp) != 1) {
            free(buffer);
            buffer = NULL;
        }
    }
    return buffer;
}

Alternatively, get rid of malloc() and let fread() read directly into an integer variable, eg:

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

int read_n_bytes(void *buf, size_t b, FILE *fp);

int main() {
    FILE *fp = fopen("flag.enc", "rb");
    if (fp == NULL) {
        // error handling...
    }

    // extract seed from flag
    uint32_t seed;
    if (read_n_bytes(&seed, sizeof(seed), fp) < 0) {
        // error handling...
    }

    srand(seed);

    fclose(fp);
}

int read_n_bytes(void *buf, size_t b, FILE *fp) {
    return (fread(buf, b, 1, fp) != 1) ? -1 : 0;
}
  •  Tags:  
  • c
  • Related