-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfmemopen_test.c
40 lines (35 loc) · 1.04 KB
/
fmemopen_test.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
#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
int main(int argc, char *argv[])
{
FILE *out, *in;
int v1, v2, v3, s;
size_t size;
char *ptr;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
in = fmemopen(argv[1], strlen(argv[1]), "r");
if (in == NULL)
handle_error("fmemopen");
out = open_memstream(&ptr, &size);
if (out == NULL)
handle_error("open_memstream");
s = fscanf(in, "%d %d %d", &v1, &v2, &v3);
if (s == -1)
handle_error("fscanf");
printf("v1 = %d, v2 = %d, v3 = %d\n", v1, v2, v3);
/* write to out */
s = fprintf(out, "%d %d %d", v1, v2, v3);
if (s == -1)
handle_error("fprintf");
fclose(in);
fclose(out);
printf("size = %ld; ptr = %s\n", (long)size, ptr);
free(ptr); /* free dynamic memory allocated by kernel when open_memstream() is called */
exit(EXIT_SUCCESS);
}