Print The File In Capital Letters


Explanation

In C file handling, we can convert the contents of a file into capital letters while reading it. In this program, the source file is opened in read mode and another file is opened in write mode. Each character is checked, and if it is a small letter, it is converted into a capital letter using ASCII values.

How It Works?

  • Step 1: Declare two file pointers for source and destination files.
  • Step 2: Open the source file in "rt" mode and destination file in "wt" mode.
  • Step 3: Read each character from the source file using fgetc().
  • Step 4: Check whether the character is between 'a' and 'z'.
  • Step 5: Convert small letters into capital letters by subtracting 32 from ASCII value.
  • Step 6: Write the converted character into the new file using fputc().
  • Step 7: Close both files using fclose().

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp, *fp2;
    char ch;

    clrscr();

    fp = fopen("file2.c", "rt");

    fp2 = fopen("filenew.c", "wt");

    if(fp == NULL || fp2 == NULL)
    {

        printf("Error opening file(s)");

        return;

    }

    while((ch = fgetc(fp)) != EOF)
    {

        if(ch >= 'a' && ch <= 'z')
        {

            ch = ch - 32;

        }

        fputc(ch, fp2);

        printf("%c", ch);

    }

    fclose(fp);

    fclose(fp2);

    getch();

}

Output

Content of file2.c:

hello india
form of program


Output After Conversion:

HELLO INDIA
FORM OF PROGRAM

Practice Exercises

Task 1: Write a C program to read a file named data.txt and convert all small letters into capital letters. Store the converted output into another file named capital.txt.

Goal: Learn how to read characters from one file, convert lowercase letters into uppercase letters, and write the modified data into another file.

💡 Hint: Open data.txt in read mode ("rt") and capital.txt in write mode ("wt"). Check each character between 'a' and 'z' and subtract 32 to convert it into a capital letter.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp, *fp2;
    char ch;

    clrscr();

    fp = fopen("data.txt", "rt");

    fp2 = fopen("capital.txt", "wt");

    while((ch = fgetc(fp)) != EOF)
    {

        if(ch >= 'a' && ch <= 'z')
        {

            ch = ch - 32;

        }

        fputc(ch, fp2);

        printf("%c", ch);

    }

    fclose(fp);

    fclose(fp2);

    getch();

}

Output

data.txt File Content:

welcome to c programming


capital.txt File Content:

WELCOME TO C PROGRAMMING
Explanation: The program reads characters from data.txt one by one. If a character is a small letter, it is converted into a capital letter using ASCII value conversion. The converted characters are then stored in capital.txt using fputc().