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().
📝 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:
- Ask for the source filename and the output filename.
- Open the source in read mode (
"r"). - Open the output in write mode (
"w") — creates the file or truncates it. - Read one character at a time from the source with
fgetc(). - Convert and write:
fputc(toupper(ch), dst). - Close both files when
fgetcreturnsEOF.
💻 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:
input.txt:
Hello, World!This file has mixed Case Letters.
file handling in c is FUN!
Running the program:
Enter the destination filename: output.txt
Converted 72 bytes to uppercase. Output: 'output.txt'.
After the program finishes, output.txt contains:
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. |
(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
chaschar:fgetcreturnsint. Usingcharmay fail to detectEOFon platforms wherecharis unsigned. - Missing the
unsigned charcast: Passing a signed negative byte totoupperis undefined behavior. Always cast first. - Forgetting that
touppertakes and returnsint: Assigning the result to acharvariable can truncate the value on systems wherecharis 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)chwhenever you pass a byte to anyctype.hfunction (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
fgetcreads exactly the bytes that are there. - On Windows, opening the destination with
"w"in text mode translates\nto\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 -gto catch type mismatches.