I have an issue with writing a uint32_t
value to a file and reading it back.
For writing it into a file, I use
uint32_t num = 2036465665 ;
FILE *fp = fopen("test.dat", "w");
fprintf(fp,"value = %" PRIu32 "\n", num);
fclose(fp);
For reading it, I first copy the contents of file into an array data[]
and then extract values line by line.
int len = 100;
char *line = malloc(len * sizeof(char));
char field[256], tmp[2];
FILE *fp = fopen("test.dat", "r");
while ( -1 != getline(&line, &len, fp)){
char *value=malloc(sizeof(char)*256);
sscanf( line, "%s %s %s", field, tmp, value);
data[i] = value;
i++;
}
fclose(fp);
To read the value of uint32_t variable, I get different values with atoi
and strtoul
with different bases, but not the exact value written into the file.
uint32_t read_num;
read_num = strtoul (data[0], NULL, 32);
This gives value of read_num as 1345324165.
read_num = (uint32_t) atoi(data[0]);
gives 3226523632
How do I get the correct value saved in the file. Is the error in (i) reading the file contents using sscanf
into string or (ii) the strtoul
vs atoi
(iii) base in strtoul()
.