简体   繁体   中英

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

I noticed that fread() and fwrite() don't work in my programmes. I wrote this little one to demonstrate it.

#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;
}

So, I have output in input.txt: ÕÃ$A33SA

(Yeah, I named file "input" but actually it is for output)

Please help

Thanks

Even though you are implying that your file is a text file (input.txt), using the "fwrite" function with the output of a structure containing floating point variables will output the data using the number of bytes required to store a floating point value in a binary fashion. For most C programs that will be four bytes. So, using your program, I ran the program and then reviewed the raw hexadecimal data using a hexadecimal file viewer. This is what I viewed.

CD CC 24 41  33 33 53 41

The eight bytes coincides with the length of two stored decimal numbers. "CD CC 24 41" represents the value "13.2" and "33 33 53 41" represents the value "10.3". To verify this I added a few lines of code to your program so that the program would read the data back in from the file and print out the values stored in that file.

#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;
}
 

When I ran the program, here is the output from the data read from the file.

Price: 13.200000, Size: 10.300000

So the data was properly stored originally.

As noted in the comments, since data is being stored in a binary fashion, you might want to open the file as a binary file (eg fopen("input.txt", "wb")).

I hope that clarifies things.

Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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