gpt4 book ai didi

c - 将 8 字节数字写入文件后如何读回?

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:56 25 4
gpt4 key购买 nike

我能够将数字的 8 字节表示形式写入文件。然而,当我回去读它时,我没有得到我期望的数字。在我下面的代码中,我试图将数字 5000 写入和读回 testfile.txt

#include <stdio.h>

int main()
{
// Open file
FILE *fp;
if ((fp = fopen("testfile.txt","w+")) == NULL)
{
// Handle error
}

// Write 8 byte number to file
long long n = 5000;
fwrite(&n, 8, 1, fp);

// Seek to EOF and check that the file is 8 bytes
fseek(fp, 0, SEEK_END);
long locend = ftell(fp);
printf("Endbyte: %ld\n",locend);

// Seek back to start of file and print out location
fseek(fp, -8, SEEK_END);
long loc = ftell(fp);
printf("Location: %ld\n",loc);

// Read and print out number
long long *out;
fread(out, 8, 1, fp);
long long num = (long long) out;
printf("Number: %lld\n", num);

/* Cleanup */
close(fp);
return(0);
}

testfile.txt 进行 hexdump 得到以下结果:

00000000  88 13 00 00 00 00 00 00                   |........|                 
00000008

1388 的十六进制值的二进制表示为 5000,这证实它被正确写入(我相信) .

不幸的是我的程序输出不一致:

Endbyte: 8                                                                    
Location: 0
Number: 140734934060848

如您所见,读回的数字与写入的数字不匹配。我假设这是我回读它的方式的问题。

最佳答案

我很惊讶它甚至可以运行而不会崩溃! fread 本质上与 fwrite 完全相同,只是方向相反。它需要一个指向内存块的指针,但您向它传递了一个未初始化的指针。

long long *out; //This is a pointer that is pointing to an undefined area of memory.
fread(out, 8, 1, fp); //fread is now writing the number to that undefined area of memory

你想要做的是创建一个普通的旧 long long 并传递对它的引用,就像你对 fwrite 所做的那样。

long long out; //This is a location in memory that will hold the value
fread(&out, 8, 1, fp); //fread is now writing the number to the area of memory defined by the 'out' variable

关于c - 将 8 字节数字写入文件后如何读回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com