C Programming • Pointers & File handling
C Programming / Writing from files

Writing from files

Notes 5 Pointers & File handling

Writing to a file means storing data from a C program into a file so that the information can be kept for later use. C provides functions such as fputc(), fputs(), and fprintf() for writing different types of data to a file.

Notes

Writing to a file means storing data from a C program into a file so that the information can be kept for later use. C provides functions such as fputc(), fputs(), and fprintf() for writing different types of data to a file.

💡 Example
FILE *fp; fp = fopen("student.txt", "w");

The file is opened in write mode so that data can be stored in it.

Writing Through a File Pointer

Once a file has been opened successfully, writing operations are performed using the file pointer rather than the filename. The file pointer identifies the file on which the operation is being performed.

💡 Example
FILE *fp; fp = fopen("data.txt", "w"); fprintf(fp, "Hello C");

Here, fp refers to the file and fprintf() writes the message into it.

fputc() Function

The fputc() function writes a single character to a file. It is similar to a character-output function, but instead of displaying the character on the screen, it writes the character to the file represented by the file pointer.

💡 Example
fputc('A', fp);

The character A is written to the file referred to by fp.

fputs() Function

The fputs() function writes a string to a file. It is useful when an entire string needs to be stored instead of writing one character at a time.

💡 Example
fputs("Welcome to C Programming", fp);

The complete string is written to the file.

fprintf() Function

The fprintf() function writes formatted data to a file. It works in a similar way to printf(), but the output is directed to the file specified by the file pointer.

💡 Example
int rollNo = 101; float marks = 82.5; fprintf(fp, "%d %.1f", rollNo, marks);

The integer and floating-point values are written to the file according to the specified format.

Opening a File for Writing

A file is normally opened using the "w" mode when new contents need to be written. If the file does not exist, it is created. If it already exists, its previous contents are replaced.

💡 Example
fp = fopen("data.txt", "w");

The file is opened for writing.

Checking the File Before Writing

Before performing a write operation, the return value of fopen() should be checked. If the file cannot be opened, fopen() returns NULL.

⚠️ Example
fp = fopen("data.txt", "w"); if (fp == NULL) { printf("Cannot open file "); return 1; }

This ensures that the program does not try to write using an invalid file pointer.

Writing Character by Character

A string or sequence of characters can be written one character at a time using fputc(). This approach is useful when the program needs control over individual characters.

💡 Example
char ch; ch = 'H'; fputc(ch, fp); ch = 'i'; fputc(ch, fp);

The characters are written individually to the file.

Writing a String

When the complete text is already available as a string, fputs() can be used to write it directly to the file.

💡 Example
char message[] = "BCA Study Portal"; fputs(message, fp);

The contents of message are written to the file.

Writing Formatted Data

When multiple values such as names, integers and marks need to be stored in a particular format, fprintf() is useful.

💡 Example
fprintf(fp, "%s %d %.1f", name, rollNo, marks);

The values are written to the file in the specified order and format.

Closing the File After Writing

After completing all write operations, the file should be closed using fclose(). Closing the file completes the file operation and releases the resources associated with it.

💡 Example
fclose(fp);

Basic Writing Flow

Declare FILE pointer ↓ Open file using fopen() ↓ Check for NULL ↓ Write data ↓ Close file using fclose()

Writing Functions at a Glance

Function Main Use
fputc() Writes one character to a file.
fputs() Writes a string to a file.
fprintf() Writes formatted data to a file.
fclose() Closes the opened file.

Practical Example

Problem Statement

Write a C program to create a text file, write a message into the file using fputs(), and close the file.

Learning Outcomes

  • Create and open a file in write mode.
  • Write a string to the file using fputs().
  • Check whether the file was opened successfully.
  • Close the file after writing.

Hint

Open message.txt using "w" mode, write a string using fputs(), and then close the file.

Theory

The fputs() function writes a string to the file represented by the file pointer. The file must be opened before writing and should be closed after the operation is complete.

Program

#include <stdio.h> int main() { FILE *fp; // open the file in write mode fp = fopen("message.txt", "w"); // check whether the file was opened successfully if (fp == NULL) { printf("Cannot open file "); return 1; } // write a message into the file fputs("Welcome to BCA Study Portal.", fp); // close the file fclose(fp); printf("Data written successfully "); return 0; }

Expected Output

Data written successfully

File Content

Welcome to BCA Study Portal.

Note

The program creates message.txt if it does not already exist. The message is written using fputs() and the file is then closed using fclose().

Practical Example — Character Writing

The fputc() function can be used when characters need to be written individually. This is the direct counterpart of reading individual characters using fgetc().

💡 Example
fputc('A', fp); fputc('B', fp); fputc('C', fp);

The characters A, B and C are written to the file one by one.

Problem Statement

Write a C program to write three characters into a text file using fputc().

Program

#include <stdio.h> int main() { FILE *fp; // open the file in write mode fp = fopen("letters.txt", "w"); // check whether the file was opened successfully if (fp == NULL) { printf("Cannot open file "); return 1; } // write characters one by one fputc('A', fp); fputc('B', fp); fputc('C', fp); fclose(fp); printf("Characters written successfully "); return 0; }

Expected Output

Characters written successfully

File Content

ABC

Note

fputc() writes one character at a time. Multiple calls can therefore be used to build a sequence of characters in a file.

Practical Example — Formatted Data

When a file needs to store values such as student name, roll number, and marks in a readable format, fprintf() can be used to write all the values together.

💡 Example
fprintf(fp, "%s %d %.1f", name, rollNo, marks);

The values are written according to the specified format.

Problem Statement

Write a C program to store a student's name, roll number, and percentage in a text file using fprintf().

Program

#include <stdio.h> int main() { FILE *fp; char name[] = "Rahul"; int rollNo = 101; float percentage = 82.5; // open the file in write mode fp = fopen("student.txt", "w"); // check whether the file was opened successfully if (fp == NULL) { printf("Cannot open file "); return 1; } // write formatted student information fprintf(fp, "%s %d %.1f", name, rollNo, percentage); fclose(fp); printf("Student record written successfully "); return 0; }

Expected Output

Student record written successfully

File Content

Rahul 101 82.5

Note

fprintf() is useful when different data types need to be written in a particular format. The same formatted data can later be read using a suitable file-reading function.

fputc(), fputs() and fprintf()

Function What It Writes Example
fputc() One character fputc('A', fp);
fputs() String fputs("Hello", fp);
fprintf() Formatted data fprintf(fp, "%d", number);

Writing vs Reading

Reading Writing
fgetc() fputc()
fgets() fputs()
fscanf() fprintf()

Important Points

📌 Remember

fgetc() → reads one character.

fputc() → writes one character.

fgets() → reads a string or line.

fputs() → writes a string.

fscanf() → reads formatted data.

fprintf() → writes formatted data.

Common Mistakes

⚠️ Mistake 1

Opening a file in "w" mode without realizing that existing contents will be overwritten.

⚠️ Mistake 2

Forgetting to check fp == NULL before writing.

⚠️ Mistake 3

Forgetting to close the file after completing the write operation.

Quick Revision

Concept Remember
Open for Writing fopen("file.txt", "w")
Character fputc()
String fputs()
Formatted Data fprintf()
Check Failure fp == NULL
Close File fclose(fp)

Important Exam Questions

Short Answer Questions

  1. What is meant by writing to a file?
  2. What is the use of fputc()?
  3. What is the use of fputs()?
  4. What is the purpose of fprintf()?
  5. What is the difference between fputc() and fputs()?
  6. What happens when a file is opened using "w" mode?
  7. Why should fopen() be checked for NULL?
  8. Why should a file be closed after writing?

Long Answer Questions

  1. Explain the process of writing data to a file in C with a suitable program.
  2. Explain fputc(), fputs() and fprintf() with suitable examples.
  3. Write a C program to create a file and write text into it.
  4. Write a C program to store formatted student information in a file.
  5. Differentiate between the reading and writing functions used in C file handling.
🎥 Recommended Learning

Watch a beginner-friendly explanation of writing to files in C programming.

▶ Watch: Writing to Files in C — Hindi

📝 Handwritten Notes

A short handwritten-style revision sheet for writing to files will be provided here.

🧠 Mind Map

Use the mind map for fopen(), file pointer, fputc(), fputs(), fprintf() and fclose().