Convert a Text File to Uppercase — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Convert the Contents of a Text File to Uppercase and Save It to a New File

In this tutorial, you'll learn how to convert the contents of a text file to uppercase and save the result to a new file using the C programming language. It's a small but practical transformation — the kind of operation you'd use to normalize user input, prepare data for a case-insensitive search, or just verify that a file round-trips correctly. The program reads the source file one character at a time with fgetc(), converts each character to uppercase with toupper(), and writes the result with fputc().

C program to convert a text file to uppercase and save it to a new file using fgetc, toupper, and fputc, with step-by-step explanation.

📝 Problem Statement

Write a program in C to convert the contents of a text file to uppercase and save it to a new file.

⚙️ How the Program Works

The program is the "copy with transformation" pattern — identical to Assignment 15's copy loop, but each byte passes through toupper before being written:

  1. Ask for the source filename and the output filename.
  2. Open the source in read mode ("r").
  3. Open the output in write mode ("w") — creates the file or truncates it.
  4. Read one character at a time from the source with fgetc().
  5. Convert and write: fputc(toupper(ch), dst).
  6. Close both files when fgetc returns EOF.

💻 Complete C Program

#include <stdio.h> #include <ctype.h> int main(void) { FILE *src, *dst; char src_name[100]; char dst_name[100]; int ch; long count = 0; printf("Enter the source filename: "); scanf("%99s", src_name); printf("Enter the destination filename: "); scanf("%99s", dst_name); /* Open source in read mode */ src = fopen(src_name, "r"); if (src == NULL) { printf("Error: Could not open '%s'.\n", src_name); return 1; } /* Open destination in write mode (creates or truncates) */ dst = fopen(dst_name, "w"); if (dst == NULL) { printf("Error: Could not create '%s'.\n", dst_name); fclose(src); return 1; } /* Read one byte, convert to uppercase, write it */ while ((ch = fgetc(src)) != EOF) { fputc(toupper((unsigned char)ch), dst); count++; } fclose(src); fclose(dst); printf("Converted %ld bytes to uppercase. Output: '%s'.\n", count, dst_name); return 0; }

🖥️ Sample Output

Assume input.txt contains a mixed-case message:

Contents of input.txt: Hello, World!
This file has mixed Case Letters.
file handling in c is FUN!

Running the program:

Console: Enter the source filename: input.txt
Enter the destination filename: output.txt
Converted 72 bytes to uppercase. Output: 'output.txt'.

After the program finishes, output.txt contains:

Contents of output.txt: HELLO, WORLD!
THIS FILE HAS MIXED CASE LETTERS.
FILE HANDLING IN C IS FUN!

Notice that the punctuation (commas, periods, exclamation marks) and the newlines are preserved — toupper passes them through unchanged. Only lowercase letters are converted.

🔍 Line-by-Line Explanation

Line / Code Explanation
#include <ctype.h> Provides toupper() (and its counterpart tolower()).
fopen(src_name, "r") Opens the source in read mode. Returns NULL if the file doesn't exist or isn't readable.
fopen(dst_name, "w") Opens the output in write mode — creates it or truncates it if it already exists.
if (dst == NULL) { fclose(src); return 1; } Closes the source before returning if the destination fails to open, avoiding a file-handle leak.
while ((ch = fgetc(src)) != EOF) Reads one byte at a time. fgetc returns int so EOF is distinguishable from byte value 0xFF.
toupper((unsigned char)ch) Converts a–z to A–Z and passes everything else through unchanged. The cast prevents undefined behavior for byte values above 127.
fputc(..., dst) Writes the converted byte to the destination.
fclose(src); fclose(dst); Flushes buffers and releases both handles. The destination is fully written only after fclose.
⚠️ Important: The cast (unsigned char)ch is not optional. The C standard says that passing a value outside the range of unsigned char to toupper (and all other ctype.h functions) is undefined behavior. If char is signed and ch holds a byte like 0xE9, calling toupper(ch) without the cast could crash or produce nonsense.

🔁 Converting to Lowercase

The symmetric operation — converting everything to lowercase — only requires changing one function call:

/* Instead of: */ fputc(toupper((unsigned char)ch), dst); /* Use: */ fputc(tolower((unsigned char)ch), dst);

Every other line is unchanged. Similarly, you could toggle case (swap upper and lower) with a small helper that checks islower/isupper and calls toupper/tolower accordingly.

📂 In-Place Conversion vs New File

This program writes to a new file, which is the safe approach. If you want to convert the file in place (overwriting the original), you cannot simply reopen the source in "w" mode — that would truncate the file before you've read from it. The correct in-place pattern is:

  • Read the source into memory or into a temporary file with the transformation applied.
  • Close the source.
  • Open the source name in "w" mode.
  • Write the transformed content back.
  • Close.

For large files, the temp-file approach is safer — see Problem 6 (delete a line) for the full temp-file swap pattern with remove and rename.

🐛 Common Pitfalls

  • Declaring ch as char: fgetc returns int. Using char may fail to detect EOF on platforms where char is unsigned.
  • Missing the unsigned char cast: Passing a signed negative byte to toupper is undefined behavior. Always cast first.
  • Forgetting that toupper takes and returns int: Assigning the result to a char variable can truncate the value on systems where char is signed.
  • Using the same file for source and destination: "w" truncates the file before you've read from it. Always use different names, or a temp file.
  • Text mode for binary files: This program is fine for text, but if the source were an image or executable, "r"/"w" on Windows would corrupt it because of line-ending translation. Use "rb"/"wb" for non-text data.
  • Ignoring fputc's return value: A full disk can cause writes to fail silently. Check the return value for production code.

💡 Tips & Best Practices

  • Use (unsigned char)ch whenever you pass a byte to any ctype.h function (toupper, tolower, isdigit, isalpha, isspace, etc.).
  • Verify the byte count after conversion — it should equal the source file size in text mode.
  • If the source file ends without a trailing newline, the output will too — no special handling is needed since fgetc reads exactly the bytes that are there.
  • On Windows, opening the destination with "w" in text mode translates \n to \r\n, so the output file will be slightly larger than the source. That's normal for text mode.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type mismatches.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 15. Copy the Contents of One Text File into Another
  • 20. Compress Multiple Spaces in a Text File
  • 11. Encrypt the Contents of a Text File
  • 10. Replace a Word with Another Word in a Text File
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 18. Build a Simple Bank Account Management System   ||   Next Problem: -->> 20. Compress Multiple Spaces in a Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.