【问题标题】:fwrite() and fread() don't work in C XCODEfwrite() 和 fread() 在 C XCODE 中不起作用
【发布时间】:2022-06-16 03:37:56
【问题描述】:

我注意到 fread() 和 fwrite() 在我的程序中不起作用。我写了这个小程序来演示它。

#include <stdio.h>

typedef struct Product {
    float size;
    float price;
} Product;

int main() {
    Product my_prod;
    my_prod.price = 13.2;
    my_prod.size = 10.3;

    FILE* file_in = fopen("/Users/piton/Desktop/UniverProg/Test/Test/input.txt", "w");
    if (file_in == NULL)
        printf("ERROR");

    fwrite(&my_prod, sizeof(Product), 1, file_in);
    
    fclose(file_in);
    return 0;
}

所以,我在 input.txt 中有输出:ÕÃ$A33SA

(是的,我将文件命名为“输入”,但实际上它是用于输出)

请帮忙

谢谢

【问题讨论】:

  • 你应该使用"wb"而不是"w"打开模式来处理二进制文件。
  • 除了文件中还有什么?
  • 嗯,根据IEEE-754 Floating Point Converter,正确的输出应该是ÍÌ$A33SA(十六进制的cd cc 24 41 33 33 53 41)。
  • 如果您使用fread 阅读此内容并打印出来会怎样?如果您检查内存位置,该结构的内容是什么?
  • 你为什么认为这是错误的?

标签: c xcode file fwrite


【解决方案1】:

即使您暗示您的文件是文本文件 (input.txt),使用“fwrite”函数和包含浮点变量的结构的输出将使用存储所需的字节数输出数据二进制方式的浮点值。对于大多数 C 程序来说,这将是四个字节。因此,使用您的程序,我运行该程序,然后使用十六进制文件查看器查看原始十六进制数据。这是我看到的。

CD CC 24 41  33 33 53 41

这八个字节与存储的两个十进制数的长度一致。 “CD CC 24 41”表示值“13.2”,“33 33 53 41”表示值“10.3”。为了验证这一点,我在您的程序中添加了几行代码,以便程序从文件中读回数据并打印出存储在该文件中的值。

#include <stdio.h>

typedef struct Product
{
    float size;
    float price;
} Product;

int main()
{
    Product my_prod;
    my_prod.price = 13.2;
    my_prod.size = 10.3;
    
    FILE* file_out = fopen("input.txt", "w"); /* I changed the name to file.out */
    if (file_out == NULL)
        printf("ERROR");
    
    fwrite(&my_prod, sizeof(Product), 1, file_out);
    
    fclose(file_out);
    
    FILE* file_in = fopen("input.txt", "r"); /* I then reopened the file to read */
    fread(&my_prod, sizeof(struct Product), 1, file_in);
    
    printf("Price: %f, Size: %f\n", my_prod.price, my_prod.size);
    
    fclose(file_in);
    
    return 0;
}
 

当我运行程序时,这是从文件中读取的数据的输出。

Price: 13.200000, Size: 10.300000

所以数据最初是正确存储的。

如 cmets 中所述,由于数据以二进制方式存储,您可能希望将文件作为二进制文件打开(例如 fopen("input.txt", "wb"))。

我希望能澄清一些事情。

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 2016-12-29
    • 2015-08-12
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多