C Program To Write In A File


♣ Try it Out ::
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 50

main()
{
    FILE *fp;
    char ch, fn[MAX];

    printf("Type a file name where you wish to write: ");
    gets(fn);

    fp = fopen(fn, "r");

    if(fp != NULL)
    {
        printf("The file exists. Overwrite it? (y/n) ");
        char con = getch();
        if(con=='n')
        {
            printf("\nType a different file name: ");
            gets(fn);
        }
    }

    fp = fopen(fn, "w");

    printf("Type your text & Press x to save: \n\n");

    while((ch=getchar()) != EOF)
    {
        if(ch == 'x') break;
        fputc(ch, fp);
        fflush(fp);
    }

    fclose(fp);

    printf("\nData has been added successfully.");

    getch();
    return(0);
}

♣ Output ::
Type a file name where you wish to write: muhit.txt
Type your text & Press x to save:

Nurul Amin Muhit
Student of Leading University
B.Sc [engg.] in CSE
x

Data has been added successfully.

♣ Downloads ::

Comments

Popular posts from this blog

C++ :: Topological Sort Algorithm (using DFS)

How to Hack Facebook Account

C++ :: Strongly Connected Components Algorithm (SCC)