-
Notifications
You must be signed in to change notification settings - Fork 0
/
StructFiles.c
45 lines (34 loc) · 936 Bytes
/
StructFiles.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DATAFILE "contacts.dat"
struct contact{
int id;
char fname[30];
char lname[30];
};
int main()
{
FILE *outfile;
FILE *infile;
struct contact input;
outfile = fopen(DATAFILE, "ab");
if (outfile == NULL){
fprintf(stderr, "\nError opening file.\n");
exit(1);
}
struct contact input1 = {3, "Harry", "Gill"};
struct contact input2 = {4, "Bella", "Gill"};
fwrite(&input1, sizeof(struct contact), 1, outfile);
fwrite(&input2, sizeof(struct contact), 1, outfile);
fclose(outfile);
infile = fopen(DATAFILE, "rb");
if (infile == NULL){
fprintf(stderr, "\nError opening file.\n");
exit(1);
}
while(fread(&input, sizeof(struct contact), 1, infile))
printf("id = %d name = %s %s\n", input.id, input.fname, input.lname);
fclose(infile);
return 0;
}