File Handling
Md. Muktar Hossain
File Handling
Create, Open, Read, and Write to files by declaring a pointer of type FILE, and
use the fopen() function.
FILE *fptr;
fptr = fopen(filename, mode);
Parameter Description
filename The name of the actual file you want to open (or create), like
[Link]
mode A single character, which represents what you want to do with the
file (read, write or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist, it will
create one for you.
FILE *fptr;
// Create a file
fptr = fopen("[Link]", "w");
// Close the file
fclose(fptr);
Write To a File
FILE *fptr;
// Open a file in writing mode
fptr = fopen("[Link]", "w");
// Write some text to the file
fprintf(fptr, "Some text");
// Close the file
fclose(fptr);
Write To a File
FILE *fptr;
// Open a file in writing mode
fptr = fopen("[Link]", "w");
// Write some text to the file
fprintf(fptr, "Hello World!");
// Close the file
fclose(fptr);
Append Content To a File
FILE *fptr;
// Open a file in append mode
fptr = fopen("[Link]", "a");
// Append some text to the file
fprintf(fptr, "\nHi everybody!");
// Close the file
fclose(fptr);
Read a File
Need to create a string that should be big enough to store the content of the
file.
FILE *fptr;
// Open a file in read mode where to store the file content
fptr = fopen("[Link]", "r");
// Store the content of the file maximum size of data to read
char myString[100]; a file pointer that is used to
// Read the content and store it inside myString read the file
fgets(myString, 100, fptr);
// Print the file content
printf("%s", myString);
// Close the file
fclose(fptr);
References
1. [Link]