Skip to content
Iampsp Blog

Iampsp Blog

I am a programming service provider

My Portfolio
Project order
Reviews
Favorite Exchange

Categories

  • C
  • C#
  • C++
  • CSS
  • Firefox Addons
  • Firefox Themes
  • HTML
  • JAVA
  • JavaScript
  • jQuery
  • Mybb Plugins
  • MySQL
  • PHP
  • Python
  • React
  • SQL

Recent Posts

  • jQuery – Get Content and Attributes
  • jQuery – Chaining
  • jQuery Callback Functions
  • jQuery Stop Animations
  • jQuery Effects – Animation

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

 

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);
Posted on 2025-04-19Author MostafaCategories CTags c programming a modern approach, c programming a modern approach pdf, c programming book, c programming course, c programming exercises, c programming language, c programming language book, c programming language pdf, c programming online, c programming tutorial, c write to file append, c write to file binary, c write to file descriptor, c write to file fprintf, c write to file in different directory, c write to file line by line, c write to file linux, c write to file open, c write to file without overwriting, c write to files

Post navigation

Previous Previous post: C Files
Next Next post: C Read Files
Proudly powered by WordPress