Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Write To Files

Write To a File

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.

Example

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); 

Consequently, upon opening the file on our computer, it appears as depicted below:

Image

 

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:

Example

fprintf(fptr, “Hello World!”);

Consequently, upon opening the file on our computer, it displays “Hello World!” rather than “Some text”.

Image

Append Content To a File

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.

Example

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); 

Consequently, upon opening the file on our computer, it appears as follows:

Image

 

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.