Let’s employ the ‘w’ mode introduced in the previous chapter once more, this time to write content to the file we’ve created.
The ‘w’ mode indicates that the file is opened for writing. To append content to it, utilize the fprintf() function, passing in the pointer variable (fptr in our example) and the desired text.
FILE *fptr;
// Open a file in writing mode // Write some text to the file // Close the file |
Consequently, upon opening the file on our computer, it appears as depicted below:
Note: Writing to a file that already exists will overwrite the old content with the new content. This behavior is significant to recognize, as it can inadvertently erase existing data. For instance: |
fprintf(fptr, “Hello World!”); |
Consequently, upon opening the file on our computer, it displays “Hello World!” rather than “Some text”.
To append content to a file without removing the existing content, utilize the ‘a’ mode.
The ‘a’ mode appends content to the end of the file.
FILE *fptr;
// Open a file in append mode // Append some text to the file // Close the file |
Consequently, upon opening the file on our computer, it appears as follows:
Note: Similar to the behavior of the ‘w’ mode, if the file doesn’t exist, the ‘a’ mode will create a new file with the appended content. |