'How to I get my program to skip the uint32_t, then start reading the rest of the binary data into structs in C?
I have included my code below. I have it reading and printing the first line of a binary file. The rest of the file is meant to be put in a struct that contains a string, float and uint32_t. While it compiles and runs fine, I am getting very wrong values when printing each struct. I'm not sure what is wrong. I am not very familiar with C, so I have a hard time seeing the issue. I have an image of my output below.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
typedef struct Record
{
char name[20];
float gpa;
uint32_t age;
} Record;
// Driver program
int main ()
{
FILE *in;
struct Record record;
in = fopen("input.bin", "rb+");
char *num = (char *)malloc(sizeof(uint32_t));
fgets(num, 2, in);
printf("%d\n", *num);
if (in == NULL)
{
return 3;
}
while(fread(&record, sizeof(struct Record), 1, in)){
printf ("name = %s gpa = %f age: %d\n", record.name, record.gpa, record.age);
}
fclose (in);
return 0;
}
I also ended up trying another approach which also doesn't work.
int main(int argc, char* argv[]){
in = fopen("input.bin", "rb+");
char *num = (char *)malloc(sizeof(uint32_t));
fgets(num, 2, in);
printf("%d\n", *num);
while(!feof(in)) {
Student st;
char name[20];
fread(&st.name, sizeof(char),1,in);
float gpa;
fread(&st.gpa, sizeof(float),1,in);
uint32_t age;
fread(&st.age, sizeof(uint32_t),1,in);
printf("%d out of %d:\n", 1, *num);
printf("Name: %s\n",st.name);
printf("GPA: %.1f (%s) \n",st.gpa, grade(gpa));
printf("Age: %" PRIu32 "\n\n\n",st.age);
}
fclose(in);
This approach gets me an error. The solution is currently going over my head.
Solution 1:[1]
char *num = (char *)malloc(sizeof(uint32_t));
fgets(num, 2, in);
printf("%d\n", *num);
fgets reads the string
not the integer number
unsigned num;
fscanf(inm "%d", &num);
printf("%d\n", *num);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | 0___________ |