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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
printf("Hello, world!\n");
fprintf(stdout, "Hello, world!\n"); // printf to a file
#include <stdio.h>
// read
int main(void)
{
FILE *fp; // Variable to represent open file
fp = fopen("hello.txt", "r"); // Open file for reading
int c = fgetc(fp); // Read a single character
printf("%c\n", c); // Print char to stdout
// read all chars until EOF
int c;
while ((c = fgetc(fp)) != EOF)
printf("%c", c);
// read line
char s[1024];
int linecount = 0;
while (fgets(s, sizeof s, fp) != NULL)
printf("%d: %s", ++linecount, s);
// formatted input
char name[1024];
float length;
int mass;
while (fscanf(fp, "%s %f %d", name, &length, &mass) != EOF) {
printf("%s whale, %d tonnes, %.1f meters\n", name, mass, length);
}
fclose(fp); // Close the file when done
}
// write
int main(void)
{
FILE *fp;
int x = 32;
fp = fopen("output.txt", "w");
fputc('B', fp);
fputc('\n', fp); // newline
fprintf(fp, "x = %d\n", x);
fputs("Hello, world!\n", fp);
fclose(fp);
}
// write binary
int main(void)
{
FILE *fp;
unsigned char bytes[6] = {5, 37, 0, 88, 255, 12};
fp = fopen("output.bin", "wb"); // wb mode for "write binary"!
// In the call to fwrite, the arguments are:
//
// * Pointer to data to write
// * Size of each "piece" of data
// * Count of each "piece" of data
// * FILE*
fwrite(bytes, sizeof(char), 6, fp);
fclose(fp);
}
|