简体   繁体   中英

Fill dat file with empty struct

My goal is to create a .dat file which contains 100 empty records. I have started the program with the following code:

#include <stdio.h>

// item structure definition
struct item {
int number; 
char name[10]; 
int quantity;
float cost;
};

// begin main function
int main(){
    int i;
    FILE *cfPtr; 
    cfPtr = fopen("hardware.dat", "w");

    struct item createEmptyRecord = {0, "", "", 0.0};


     for (i=0;i<100;i++){
        // the fwrite function in the stdio.h library 
        // declartion size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
        fwrite (&createEmptyRecord, sizeof (struct item), 1, cfPtr);
    } // end for loop

    fclose(cfPtr);

} // end main function

I am getting a .dat output but when I open it to check all of the items are NULL and they have the caracters below. How can I check to see if this is garbage values or I actually initalized 100 structs to blank?

?@@ ?@@ ?@@ ?@@ ?@@ ?@@ ?@@ ?@@ ?@@ ?@@

struct item createEmptyRecord = {0, "", "", 0.0};

Note that here you are passing "" to initialize an int member. The string literal "" is not the same as NULL. If you increase the warning level of your compiler, it should warn you about a const char* being converted to a int .

The correct way to initialize a struct to all-zero is:

struct item createEmptyRecord = {0};

Alternatively you can use memset :

struct item createEmptyRecord;
memset(&createEmptyRecord, 0, sizeof(createEmptyRecord));

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