In C, to edit a file, we can just declare a pointer type file and then use
the fopen() function.
Example:
FILE *fptr fptr = fopen(filename, mode);
Description:
filename: the name of the file you want to openmode: can be chosen from (w: write, a: append, or r: read)
Write mode (w) is a mode that opened a file to write into it.
Note that we write to it, not append it. So, when we open an existing document
and write into it, the previous content will be deleted and replaced by
the new content we just wrote in. To write something, we just need to
use fprint() function.
Syntax: fprintf(pointer_name, "text we want to write");
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; }
Append mode (a) is used when we want to write something new in the file
without replacing the old content. The append mode uses the same
fprintf() function as the write mode.
Syntax: fprintf(pointer_name, "text we want to write");
Example:
#include<stdio.h> int main() { FILE *fptr; // Open a file in append mode fptr = fopen("filename.txt", "a"); // Append some text to the file fprintf(fptr, "\nHi everybody!"); // Close the file fclose(fptr); return 0; }
Read mode (r) is used to access a file content into our program. Read in C
requires the fgets() function and an array of strings
to store the content of the file.
fgets()
only can get a single line of content, so to get multiple lines of content,
we need to do looping.
Syntax:
char string_name[string_size]; fgets(string_name, string_size, pointer_name);
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 the file content printf("%s", myString); // Close the file fclose(fptr); return 0; }