Union
Storage classes

File handling

File handling

file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.

File is used to store data. In this topic, we will learn about reading data from a file and writing data in the file.

PROGRAM FOR FILE OPEN/FILE WRITE AND FILE CLOSE IN C LANGUAGE:

Lets try an example through which we can understand the concept of how to open the file, how to write the file and how to close the file in c language.

/ * Open, write and close a file : */
# include<stdio.h>
# include<string.h>
 
int main( )
{
    FILE *fp ;
    char data[50];
    // opening an existing file
    printf( "Opening the file test.c in write mode" ) ;
    fp = fopen("test.c", "w") ;
    if ( fp == NULL )
    {
        printf( "Could not open file test.c" ) ;
        return 1;
    }
    printf( "\n Enter some text from keyboard” \
             “ to write in the file test.c" ) ;
    // getting input from user
    while ( strlen ( gets( data ) ) > 0 )
    {
        // writing in the file
        fputs(data, fp) ;   
        fputs("\n", fp) ;
    }
    // closing the file
    printf("Closing the file test.c") ;
    fclose(fp) ;
    return 0;        
}

Opening the file test.c in write mode
Enter some text from keyboard to write in the file test.c
Hai, How are you?
Closing the file test.c

PROGRAM FOR FILE OPEN/FILE READ AND FILE CLOSE IN C LANGUAGE:

Lets try an example through which we can understand the concept of how to open the file, how to read the file and how to close the file in c language.

/* Open, Read and close a file: reading string by string */
 
# include<stdio.h>
int main( )
{
         FILE *fp ;
         char data[50] ;
         printf( "Opening the file test.c in read mode" ) ;
         fp = fopen( "test.c", "r" ) ;
         if ( fp == NULL )
         {
                 printf( "Could not open file test.c" ) ;
                 return 1;
         }
         printf( "Reading the file test.c" ) ;
         while( fgets ( data, 50, fp ) != NULL )
         printf( "%s" , data ) ;
         printf("Closing the file test.c") ;
         fclose(fp) ;
         return 0;
}

Opening the file test.c in read mode
Reading the file test.c
Hai, How are you?
Closing the file test.c

Comments are closed.