-
Notifications
You must be signed in to change notification settings - Fork 0
/
(12.06.23) File Handling
79 lines (57 loc) · 2.47 KB
/
(12.06.23) File Handling
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
73
74
75
76
77
78
#include <stdio.h>
int main() {
FILE *file; // Declare a pointer to a FILE structure
char filename[100]; // Store the filename
char ch; // Store each character read from the file
printf("Enter the filename: ");
scanf("%s", filename); // Read the filename from the user
// Open the file in "r" mode (read mode)
file = fopen(filename, "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Read and print the file contents
printf("File contents:\n");
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch); // Print each character read from the file
}
// Close the file
fclose(file);
return 0;
}
#include <stdio.h>
int main() {
FILE *file; // Declare a pointer to a FILE structure
char filename[100]; // Store the filename
char content[1000]; // Store the content to be written to the file
printf("Enter the filename: ");
scanf("%99s", filename); // Read the filename from the user
// Open the file in "w" mode (write mode)
file = fopen(filename, "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
printf("Enter content to write to the file (max 1000 characters):\n");
// Clear the input buffer
int c;
while ((c = getchar()) != '\n' && c != EOF);
// Read content from the user using fgets()
fgets(content, sizeof(content), stdin);
// Write the content to the file using fputs()
fputs(content, file);
// Close the file
fclose(file);
printf("Content written to the file successfully.\n");
return 0;
}
File Modes
"r": Opens a file for reading. The file must exist.
"w": Opens a file for writing. If the file exists, its previous contents are truncated. If the file does not exist, a new file is created.
"a": Opens a file for appending. Data is written at the end of the file. If the file does not exist, a new file is created.
"r+": Opens a file for both reading and writing. The file must exist.
"w+": Opens a file for both reading and writing. If the file exists, its previous contents are truncated. If the file does not exist, a new file is created.
"a+": Opens a file for both reading and appending. Data can be read or written at any position in the file. If the file does not exist, a new file is created.