Read mpq_t from a binary file

129 views Asked by At

I have written mpq_t to a binary file called "data", and now I am trying to read mpq_t from the file one by one, but I kept having segfault at the line: gmp_printf("%Qd\n", buf). I've been debugging for a while but couldn't figure out where went wrong.

int main(){

    FILE *fp = fopen("data", "rb");
    if (fp == NULL){
            perror("FILE open failed");
            exit(1);
    }

    mpq_t buf;
    mpq_init(buf);

    while (fread(&buf, sizeof(mpq_t), 1, fp) == 1){
            gmp_printf("%Qd\n", buf);
    }

    fclose(fp);
    return 0;
}

It seems that I have a memory issue with buf after reading from the file. I have also tried mallocing instead of initiating, but it did not work either.

    mpq_t *buf = (mpq_t *)malloc(sizeof(mpq_t));

    if (buf == NULL){
            perror("malloc failed");
            exit(1);
    }

    while (fread(buf, sizeof(mpq_t), 1, fp) == 1){
            gmp_printf("%Qd\n", *buf);
    }
1

There are 1 answers

0
Ashley On BEST ANSWER

Use gmp_fprintf and gmp_fscanf to write and read:

   gmp_fprintf (FILE *fp, const char *fmt, ...)
   gmp_fscanf (FILE *fp, const char *fmt, ...)