HomeC ProgrammingC Program to Convert the Content of File to Lowercase

C Program to Convert the Content of File to Lowercase

This C program takes the name of an input file as user input and converts its content to lowercase. The converted content is then saved in a new file called ‘output.txt’.

Problem Statement

Write a C program that reads the content of a file, converts it to lowercase, and saves the modified content in another file.

C Program to Convert the Content of File to Lowercase

#include <stdio.h>
#include <ctype.h>

#define MAX_SIZE 1000

int main() {
    FILE *inputFile, *outputFile;
    char fileName[100], ch;

    printf("Enter the name of the input file: ");
    scanf("%s", fileName);

    // Open the input file in read mode
    inputFile = fopen(fileName, "r");
    if (inputFile == NULL) {
        printf("Cannot open file '%s'\n", fileName);
        return 1;
    }

    // Open the output file in write mode
    outputFile = fopen("output.txt", "w");
    if (outputFile == NULL) {
        printf("Cannot create output file\n");
        return 1;
    }

    // Read characters from input file and convert to lowercase
    while ((ch = fgetc(inputFile)) != EOF) {
        fputc(tolower(ch), outputFile);
    }

    printf("Content converted to lowercase and saved to 'output.txt'\n");

    // Close the files
    fclose(inputFile);
    fclose(outputFile);

    return 0;
}

How it works

  1. The program starts by asking the user to enter the name of the input file.
  2. It then attempts to open the input file in read mode using fopen(). If the file cannot be opened, an error message is displayed, and the program terminates.
  3. Next, it creates an output file called ‘output.txt’ using fopen() in write mode. If the output file cannot be created, an error message is displayed, and the program terminates.
  4. The program reads each character from the input file using fgetc() in a loop until it reaches the end of the file (EOF).
  5. Inside the loop, each character is converted to lowercase using tolower() function, and the lowercase character is written to the output file using fputc().
  6. After the loop finishes, the program displays a success message and closes both the input and output files using fclose().
  7. Finally, the program terminates with a return value of 0.

Input / Output

C Program to Convert the Content of File to Lowercase

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...