Pr.Pg Next Pg

File Handling Examples tutorials


 

Example: C program for creating the File

 Sam Madam

#include<stdio.h>

int main()

{

FILE *f;

f = fopen("C:\\C.txt","w");

return 0;

}

 

 

  • Note: The above program will create an empty C.txt file in C drive of your Computer System

 

 

Example: C program to write the file

Sam Madam

// C program to write the file

#include<stdio.h>

void main()

{

FILE *fp;

fp = fopen("C:\\C.txt","w");

fprintf(fp,"Hello C IO");

}

 

 

  • Note: The above program will write the content to the C.txt file

 

 

Example: C program for reading the content of the file

Sam Madam

// C program for reading the content of the file

#include<stdio.h>

 

void main()

{

FILE *fp;

int c ;

 

fp = fopen("C:\\C.txt","r");

c = getc(fp) ;

while (c!=EOF)

{

putchar(c);

c=getc (fp);

}

 

fclose(fp);

}

Output

Hello C IO

 


 

Example: C Program to accept a string from the user and write it in a file using the concepts of file handling.

Sam Madam

/* C Program to accept a string from the user and write it in a file using the concepts of file handling.*/

#include<stdio.h>

void main()

{

FILE *fp;

char ch;

fp=fopen("C:\\NewFile.txt","w");

printf("Enter Text to be store in the File :");

while((ch=getchar())!=EOF)

putc(ch,fp);

fclose(fp);

}

Output

Enter Text to be store in the File :This is new File Data

  • Note: After entering the text and closing the output screen check the NewFile.txt in C drive.

Pr.Pg border                                              Next Pg