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

How do I read back an 8 byte number after writing it to a file?

我能够将数字的 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

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

out 是一个指针,需要先取消引用才能分配给 num。

out 是一个指针,因此它必须指向有效地址,然后才能为其赋值,要获取它的值,您必须使用 & 而不是强制转换。
这是一个正确的代码:

long long num;
fread(&num, 8, 1, fp);
printf("Number: %lld\n", num);

还有一件事,请更正您的 close 功能,如下所示

fclose(fp);

请注意 close 使用文件描述符,fclose 使用 FILE *

我很惊讶竟然 运行 没有崩溃! 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