So far, we have learned about 2 modes: “r” (for reading) and “w” (for writing). Let’s learn about a few more modes.
append “a”
Let’s take a short recap on “w” mode at first so that you can better understand “a”.
You can clearly understand the point 2 is problematic as it erases important information. To mitigate the problem, here comes “a”. What it does
Let’s take a look. We have a file file.txt at D:\\zeroneincore
We want to keep the content and also add something new. For that reason, “a” mode is used. So lets take a look at the code
#include <stdio.h>
void main()
{
FILE* ptr;
char data[100];
ptr = fopen("D:\\zeroneincore\\file.txt", "a");
fprintf(ptr," Good Morning");
fclose(ptr);
}
After running this code, If you open the file, you will see Good Morning is added at the end of the file keeping the previous contents as it is.
“w+”
If we make a file pointer “w”, we can only write with it. We can not read with this. For reading, you need to declare a new file pointer with mode “r”. Here comes “w+”.
Take a look at the code
01.#include <stdio.h>
02.
03.void main()
04.
05.{
06.
07. FILE* ptr;
08.
09. char data[100];
10.
11. ptr = fopen("D:\\zeroneincore\\file1.txt", "w+");
12.
13. //writing
14.
15. fprintf(ptr,"Good");
16.
17. fprintf(ptr," Morning");
18.
19. fseek(ptr, 0, SEEK_SET); //points ptr at the beginning
20.
21. //reading
22. while (fscanf(ptr,"%s", data) != EOF)
23.
24. {
25. printf("%s ",data);
26. }
27. fclose(ptr);
28.}
So that’s our code. After executing line 11, our file pointer ptr will be at the beginning (read this post if you forget). Where will our ptr be after line 15? See this
And similarly after executing line 17, our ptr will be at
Now we have done with our writing. Now we want to read the file from the beginning. From where? From the beginning. But right now, our ptr is pointing at the end of the file. Let’s point it back at the beginning of the file. To do this, we have used fseek() built-in function at line 19. (you can move the file pointer using this function. More detailed). After line 19, the ptr will be at
Then the rest of the task is nothing new to you. We have just written the code for reading from a file.
“r+”
Let’s take a look at it’s features
You can take a look at the previous code. Just write r+ instead of w+ at line 7.
“a+”
This is almost similar to the w+ . Let’s take a look at it’s features
You can take a look at the previous code. Just write r+ instead of a+ at line 7.
I hope I have explained it better. You can also check out the book Let Us C. It is amazing to read.
Thank you!