C Program to Write Data in a File

Get Certified in C Programming and Take Your Skills to the Next Level

Program 1

// Program for write data in file 
#include<stdio.h>
#include<conio.h>
int main()
{
     system("cls");
     char ch;
     FILE *fp=NULL;
     fp=fopen("d://mydata/student.txt","w");
     if(fp==NULL)
      printf("\nFile not created");
     else 
     {
       printf("\n Enter a character"); 
       ch=getche();
       fputc(ch,fp);
       printf("\n File created");
       fclose(fp);
     } 
     return 0;
}

Program 2

// Program for write string data in file 
#include<stdio.h>
#include<conio.h>
int main()
{
     system("cls");
     char ch;
     FILE *fp=NULL;
     fp=fopen("d://mydata/mystring.txt","w");
     if(fp==NULL)
      printf("\nFile not created");
     else 
     {
       printf("\n Enter a string"); 
       while((ch=getche())!='0')
       {
           fputc(ch,fp);
       } 
       printf("\n File created");
       fclose(fp);
     } 
     return 0;
}

Program 3

// Program for read single character data from file 
#include<stdio.h>
#include<conio.h>
int main()
{
     system("cls");
     char ch;
     FILE *fp=NULL;
     fp=fopen("d://mydata/mystring.txt","r");
     if(fp==NULL)
      printf("\nFile not found");
     else 
     {
       while((ch=fgetc(fp))!=EOF)
       {
           printf("%c",ch);  
       }  
       fclose(fp);
     } 
     return 0;
}

 

 

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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