forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_io_examples.c
More file actions
38 lines (32 loc) · 925 Bytes
/
file_io_examples.c
File metadata and controls
38 lines (32 loc) · 925 Bytes
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
/*
* file_io_examples.c
* Demonstrates basic file read/write in C.
* Creates (or overwrites) "sample_output.txt", writes sample lines,
* then reopens and reads them back to stdout.
* Compile: gcc -std=c11 -Wall -Wextra -o file_io_examples file_io_examples.c
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *filename = "sample_output.txt";
FILE *f = fopen(filename, "w");
if (!f) {
perror("fopen for write");
return EXIT_FAILURE;
}
fprintf(f, "Hello from file_io_examples!\n");
fprintf(f, "This file was written by a C program.\n");
fclose(f);
f = fopen(filename, "r");
if (!f) {
perror("fopen for read");
return EXIT_FAILURE;
}
printf("Contents of %s:\n", filename);
char buffer[256];
while (fgets(buffer, sizeof(buffer), f)) {
fputs(buffer, stdout);
}
fclose(f);
return EXIT_SUCCESS;
}