C Write To Files

C Tutorial

C Write to Files Tutorial

In C language, writing data to files is done using the Standard I/O library <stdio.h>.
You can write, overwrite, or append data in text and binary files.


 Basic Steps to Write to a File in C

  1. Declare file pointer

  2. Open file in write mode

  3. Write data to file

  4. Close file


 File Open Modes for Writing

ModePurpose
"w"Write (creates / overwrites file)
"a"Append (adds data at end)
"wb"Write binary file
"ab"Append binary file

 Writing to File Using fputc() (Character)


 

  •  Writes characters one by one

Writing to File Using fputs() (String)


 

  •  Writes string data
  •  No automatic newline

 Writing to File Using fprintf() (Formatted Output)


 

  •  Most commonly used
  •  Similar to printf()

 Writing Multiple Lines to File


 


 Appending Data to a File


 

  •  Old data remains safe
  •  New data added at end

 Writing Binary File Using fwrite()


 

  •  Used in binary & embedded systems

Writing struct to File (Interview Favorite)


 


Common Mistakes & Solutions

1. Forgetting to close file
2. Always use fclose()

3. Opening file in wrong mode
4. Use "w" or "a" properly

5. Not checking file pointer
6. Always check fp == NULL


 Interview Questions (Very Important)

  1. Difference between "w" and "a"

  2. Difference between fputs() and fprintf()

  3. What happens if file exists in "w" mode?

  4. How to write binary data?

  5. How to write struct into file?


Summary

  •  Writing to files is essential in C
  • Choose correct write function
  •  Use append mode to protect old data
  •  Critical for placements & projects

You may also like...