🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C Notes
Topic #71

C Write To Files


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

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

image

Note: If you write to a file that already exists, the old content is deleted, and the new content is inserted. This is important to know, as you might accidentally erase existing content. For example: Example fprintf(fptr, "Hello World!"); As a result, when we open the file on our computer, it says "Hello World!" instead of "Some text":


Append Content To a File

If you want to add content to a file without deleting the old content, you can use the a mode.

The a mode appends content at 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);

image

Note: Just like with the w mode; if the file does not exist, the a mode will create a new file with the "appended" content.

Want to go beyond the notes?

Join CodingNow 2.0's C course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C Write To Files – FAQs

Quick answers about learning C Write To Files in C.

This free note from CodingNow 2.0 explains C Write To Files in C — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C topic on CodingNow 2.0, including C Write To Files, is 100% free with no signup required.
With focused practice, most students grasp C Write To Files in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now