Introduce old redir program
[lcapit-junk-code.git] / books / apue / freadwrite.c
blob4d26c6fbed39eaa32cb5384dfc7e1e85f1cda084
1 /*
2 * A fread() and fwrite() example
3 */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #define NAME_MAX 32
11 struct data {
12 int id;
13 int count;
14 char name[NAME_MAX];
17 static void usage(const char *progname)
19 printf("Usage: %s < -w | -r > < filename >\n", progname);
22 int main(int argc, char *argv[])
24 size_t ret;
25 FILE *file;
26 int i;
27 struct data data;
28 char *filepath, *progname;
30 if (argc != 3) {
31 fprintf(stderr, "Wrong number of arguments\n");
32 usage(argv[0]);
33 exit(1);
36 progname = argv[0];
37 filepath = argv[2];
38 if (!memcmp(argv[1], "-w", 2)) {
39 struct data datav[2];
42 * Write the structures using fwrite()
45 file = fopen(filepath, "w+");
46 if (!file) {
47 perror("fopen()");
48 exit(1);
51 /* fill datav[] */
52 memset(datav, 0, sizeof(data));
53 datav[0].id = 0;
54 datav[0].count = 42;
55 strncpy(datav[0].name, "luiz", NAME_MAX);
57 datav[1].id = 1;
58 datav[1].count = 666;
59 strncpy(datav[1].name, "capitulino", NAME_MAX);
61 ret = fwrite((void *) datav, sizeof(struct data),
62 2, file);
63 if (ret != 2) {
64 perror("fwrite()");
65 exit(1);
68 goto out;
72 * Write the structures using fwrite()
75 file = fopen(filepath, "r");
76 if (!file) {
77 perror("fopen()");
78 exit(1);
81 for (i = 0; i < 2; i++) {
82 ret = fread((void *) &data, sizeof(data), 1, file);
83 if (ret != 1) {
84 if (feof(file)) {
85 fprintf(stderr, "finished reading\n");
86 goto out;
89 perror("fread()");
90 exit(1);
93 printf("id = %d\ncount = %d\nname = %s\n\n", data.id,
94 data.count, data.name);
97 out:
98 fclose(file);
99 return 0;