繁体   English   中英

fwrite() 和 fread() 在 C XCODE 中不起作用

[英]fwrite() and fread() don't work in C XCODE

我注意到 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

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

请帮忙

谢谢

即使您暗示您的文件是文本文件 (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

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

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

我希望这能澄清事情。

问候。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM