×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to capitalize the first letter of every word in a file

Here, we are going to learn how to capitalize the first letter of every word in a file using C program?
Submitted by Nidhi, on August 26, 2021

Problem statement

Here, we will read data from a file and capitalize the first letter of every word and update data into the file.

Capitalizing the first letter of every word in a file

The source code to capitalize the first letter of every word in a file is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to capitalize the first letter
// of every word in a file

#include <stdio.h>
#include <string.h>

void writeData(char* str)
{
    FILE* fp;

    //Write data into a file.
    fp = fopen("includehelp.txt", "w");
    if (fp == NULL)
        return;

    fwrite(str, 1, strlen(str), fp);
    fclose(fp);
}

void readData(char* str)
{
    FILE* fp;

    char ch = 0;
    int cnt = 0;

    fp = fopen("includehelp.txt", "r");
    if (fp == NULL)
        return;

    ch = fgetc(fp);
    while (ch != EOF) {
        str[cnt++] = ch;
        ch = fgetc(fp);
    }
    str[cnt] = 0;
    fclose(fp);
}

int main()
{
    char wrtStr[32] = "this is india";
    char readStr[32];

    int flg = 1;
    int cnt = 0;

    writeData(wrtStr);
    readData(readStr);

    while (readStr[cnt] != 0) {
        if (flg == 1 && readStr[cnt] != 0x20) {
            readStr[cnt] = readStr[cnt] - 32;
            flg = 0;
        }

        if (readStr[cnt] == 0x20 && flg == 0)
            flg = 1;

        cnt++;
    }

    writeData(readStr);

    memset(readStr, 0x00, sizeof(readStr));
    readData(readStr);

    printf("Original data from file: %s\n", wrtStr);
    printf("Update data from file: %s\n", readStr);

    return 0;
}

Output

Original data from file: this is india
Update data from file: This Is India

Explanation

Here, we created three function readData(), writeData(), and main(). The readData() function is used to read data from file. The writeData() function is used to write data into file.

In the main() function, we wrote data into the file. Then we read data from the file and capitalize the first letter of every word and update data into the file. At last, we printed original data and updated data.

C File Handling Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.