代码之家  ›  专栏  ›  技术社区  ›  mibacode

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

  •  1
  • mibacode  · 技术社区  · 10 年前

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

    正在执行一个十六进制转储 测试文件.txt 给我以下信息:

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

    十六进制值的二进制表示 13 88 制作 5000 ,这证实它写得正确(我相信)。

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

    Endbyte: 8                                                                    
    Location: 0                                                             
    Number: 140734934060848
    

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

    3 回复  |  直到 10 年前
        1
  •  3
  •   Kaslai    10 年前

    我很惊讶它居然能跑而不撞! 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 并传递一个引用,就像您使用 写入文件 .

    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
    
        2
  •  1
  •   Randy Kamradt Sr.    10 年前

    out是一个指针,需要在将其分配给num之前取消引用。

        3
  •  1
  •   Parham Alvani    10 年前

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

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

    还有一件事,请纠正 close 功能如下

    fclose(fp);
    

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