Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting an array of structs to a binary file in C
    primarykey
    data
    text
    <p>I have an array of structs I would like to write to a binary file. I have a write.c program and a read.c program. The write.c program seems to be working properly but when I run the read.c program I get a segmentation fault. I'm new to C so It would be great if someone could look over my code for any obvious errors. I promise it's not too long :)</p> <p>write.c:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; struct Person { char f_name[256]; char l_name[256]; int age; }; int main(int argc, char* argv[]) { struct Person* people; int people_count; printf("How many people would you like to create: "); scanf("%i", &amp;people_count); people = malloc(sizeof(struct Person) * people_count); int n; for (n = 0; n &lt; people_count; n++) { printf("Person %i's First Name: ", n); scanf("%s", people[n].f_name); printf("Person %i's Last Name: ", n); scanf("%s", people[n].l_name); printf("Person %i's Age: ", n); scanf("%i", &amp;people[n].age); } FILE* data; if ( (data = fopen("data.bin", "wb")) == NULL ) { printf("Error opening file\n"); return 1; } fwrite(people, sizeof(struct Person) * people_count, 1, data); fclose(data); return 0; } </code></pre> <p>read.c:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; struct Person { char f_name[256]; char l_name[256]; int age; }; int main(int argc, char* argv[]) { FILE* data; if ((data = fopen("data.bin", "rb")) == NULL) { printf("Error opening file\n"); return 1; } struct Person* people; fread(people, sizeof(struct Person) * 1/* Just read one person */, 1, data); printf("%s\n", people[0].f_name); fclose(data); return 0; } </code></pre> <p>Thanks for the help!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload