-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path02_fopen.c
More file actions
50 lines (40 loc) · 1.2 KB
/
02_fopen.c
File metadata and controls
50 lines (40 loc) · 1.2 KB
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
/*
Project #02 (CSeries)
02_FOPEN.C
----------
Description:
This demostrate the use of fopen in C.
Function:
FILE *fopen( const char *filename, const char *mode );
Visit: https://en.cppreference.com/w/c/io/fopen
Edited By: J3
Date: Nov, 2021
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int is_ok = EXIT_FAILURE;
const char* fname = "unique_name.txt"; // or tmpnam(NULL);
FILE* fp = fopen(fname, "w+");
if(!fp) {
perror("File opening failed");
return is_ok;
}
fputs("Hello, world!\n", fp);
rewind(fp); // sets the file position to the beginning of the file for the stream pointed to by stream.
// It also clears the error and end-of-file indicators for stream.
int c; // note: int, not char, required to handle EOF
while ((c = fgetc(fp)) != EOF) { // standard C I/O file reading loop
putchar(c);
}
if (ferror(fp)) {
puts("I/O error when reading");
} else if (feof(fp)) {
puts("End of file reached successfully");
is_ok = EXIT_SUCCESS;
}
fclose(fp);
remove(fname);
return is_ok;
}