C Writing Text Files

Intermediate
6 min read
Updated: Nov 2026
1 example

What Is Writing Text Files?

fputc(ch, fp) writes one character, fputs(str, fp) writes a string without adding a newline, and fprintf(fp, format, ...) writes formatted text. Output is buffered, so call fclose or fflush to make sure it reaches the file.

Remember
fputc('A', fp);
fputs("text\n", fp);
fprintf(fp, "%d squared is %d\n", n, n * n);
fflush(fp);     /* force buffered data out */

Cheat Sheet

Keep these facts handy while you work with Writing Text Files in C.

TopicDetail
fputcOne character
fputsNo newline added
fprintfFormatted
Bufferingfflush / fclose

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Formatted File I/O.

Example 1 — Write a table of squares

Write with fprintf, then read the first line back.

C
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("squares.txt", "w");
    if (!fp) return 1;
    for (int n = 1; n <= 3; n++) {
        fprintf(fp, "%d squared is %d\n", n, n * n);
    }
    fclose(fp);
    printf("wrote 3 lines\n");

    char line[64];
    fp = fopen("squares.txt", "r");
    if (!fp) return 1;
    if (fgets(line, sizeof line, fp)) printf("first: %s", line);
    fclose(fp);
    return 0;
}

How It Works

  1. fprintf works like printf but targets a file.
  2. fclose makes sure everything is on disk.
  3. The second open reads the first line back.

Edge Cases & Pitfalls

Check these before relying on Writing Text Files in real programs.

nl

Forgetting newlines

fputs does not append \n, unlike puts.

loss

Output lost on crash

Buffered data is lost if the program crashes before fflush or fclose.

Key Takeaways

  • fprintf: most flexible.
  • fputs: no newline.
  • Flush: before risky operations.

One line: fputc(ch, fp) writes one character, fputs(str, fp) writes a string without adding a newline, and fprintf(fp, format, ...) writes formatted text.

Frequently Asked Questions

puts writes to stdout and appends a newline. fputs writes to the stream you give it and does not add a newline.
Open it in "a" mode so every write goes to the end.
Continue with "C Formatted File I/O" next. Write and parse records with fprintf and fscanf. The C File Handling hub lists every topic in order.

Next: Formatted File I/O

Write and parse records with fprintf and fscanf.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful