C Program to Read Content from User & Write to File

Question: write a program in C to read content from user and write it to file named "data.txt" until user presses new line and read stored content from file and display it.

C Source Code: Read Content from User & Write to File

In this program “data.txt” will be created by program and if it already exist then its content will be erased.


#include<stdio.h>
#include<stdlib.h>

int main()
{
    FILE *fptr;
    char ch;

    /* Opening file in read mode */
    fptr = fopen("data.txt","w+");
    if(fptr==NULL)
    {
        printf("Can't open file. Make sure file exits.\n");
        exit(1);
    }

    /* Reading character and storing them in file
    until user enters n */
    printf("Start typing something....\n\n");
    do
    {
        ch = getche();
        fputc(ch,fptr);
    }while(ch!='\r'); /* don't use \n */

    /* Taking file pointer back to begining of file */
    rewind(fptr);
    
    printf("\n\nWritten content in file is:\n");
    
    /* Reading file and displaying */
    do
    {
        ch = fgetc(fptr);
        putchar(ch);
    }while(ch!=EOF);

    /* Closing file */
    fclose(fptr);
    printf("\n\nProgram completed. Press any key to continue...");

    return 0;
}

Output

The output of the above program is:

Start typing something....

A soul in tension that is learning to fly, 
Condition grounded but determined to try.↲

Written content in file is:
A soul in tension that is learning to fly, 
Condition grounded but determined to try.

Program completed. Press any key to continue...