我在寫一個uint32_t
值到文件並讀回來時遇到了問題。 爲了寫入到文件中,我使用在讀取保存在文件中的uint32_t變量時出錯
uint32_t num = 2036465665 ;
FILE *fp = fopen("test.dat", "w");
fprintf(fp,"value = %" PRIu32 "\n", num);
fclose(fp);
爲了讀取它,我第一文件中的內容複製到一個數組data[]
,然後通過線提取值線。
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);
讀取uint32_t的變量的值,我得到不同的價值觀與atoi
和strtoul
與不同的基礎,但不是精確值寫入文件。
uint32_t read_num;
read_num = strtoul (data[0], NULL, 32);
這給read_num的價值爲1345324165.
read_num = (uint32_t) atoi(data[0]);
給人3226523632
我如何保存在文件中正確的值。 (i)是否使用sscanf
將文件內容讀入字符串或(ii)strtoul
vs atoi
(iii)基於strtoul()
中的錯誤。
strtoul(data [0],NULL,32); - 你的基數是32?我會查找如何正確使用此功能;基於我已經瞥了一眼應該是10,而不是32. – MateoConLechuga
另外,我會建議使用EOF而不是-1作爲getline的返回檢查。 – MateoConLechuga
@MateoConLechuga:實際上,在POSIX中定義了['getline()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html)來返回-1而不是'EOF',所以使用'-1'是正確的。 –