C LANGUAGE File Handling
C LANGUAGE File Handling
Parameter Description
filename The name of the actual file you want to open (or create),
like filename.txt
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:
Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
This will close the file when we are done with it.
Write To a File
Let's use the w mode from the previous chapter again, and write something to
the file we just created.
The w mode means that the file is opened for writing. To insert content to it,
you can use the fprintf() function and add the pointer variable (fptr in our
example) and some text:
Example
#include <stdio.h>
int main() {
FILE *fptr;
// Open a file in writing mode
fptr = fopen("filename.txt", "w");
// Write some text to the file
fprintf(fptr, "Some text");
// Close the file
fclose(fptr);
return 0;
}
Read Files
In the previous chapter, we wrote to a file using w and a modes inside
the fopen() function.
Example
FILE *fptr;
Example
#include <stdio.h>
int main() {
FILE *fptr;
// Open a file in read mode
fptr = fopen("filename.txt", "r");
// Store the content of the file
char myString[100];
// Read the content and store it inside myString
fgets(myString, 100, fptr);
// Print file content
printf("%s", myString);
// Close the file
fclose(fptr);
return 0;
}