File operations
in C involve various functions provided by the stdio.h library. Here's an overview of common file operations:
Opening a File:
fopen:
Opens a file with a specified mode (read, write, append, etc.).
FILE
*
fptr
=
fopen
("
example.txt", "r"
);
Writing a File:
fprintf:
Writes formatted data to a file.
fprintf
(
fptr
, "
This is a line of text
");
fputc and fputs:
a character or string to a file.
fputc
('
A
',
fptr
);
fputs
("
Hello, File!
", fptr);
Reading from a File:
fscanf:
Reads formatted data from a file.
fscanf
(
fptr
, "%s",
buffer
);
fgetc and fgets:
Reads a character or a line from a file.
char ch = fgetc(fptr); // Read a character
fgets(buffer, sizeof(buffer), fptr); // Read a line
Closing a File:
fclose:
Closes the file.
fclose(fptr);
Example of File Handling
#include
<stdio.h>
Copy Code
int
main
() {
FILE
*
filePointer
;
char
data
[100];
filePointer
=
fopen
("example.txt", "w");
if
(
filePointer
==
NULL
) {
printf
("Error opening the file.
");
return
1;
}
fprintf
(
filePointer
, "Hello, File Handling in C!");
fclose
(
filePointer
);
filePointer
=
fopen
("example.txt", "r");
if
(
filePointer
==
NULL
) {
printf
("Error opening the file for reading.
");
return
1;
}
fscanf
(
filePointer
, "%[^
]",
data
);
printf
("Content from the file: %s
",
data
);
fclose
(
filePointer
);
return
0;
}
This program does the following:
1. Opens a file named "example.txt" for writing.
2. Writes the string "Hello, File Handling in C!" to the file.
3. Closes the file.
4. Opens the same file for reading.
5. Reads the content from the file and displays it on the console.
6. Closes the file.