Data file Handing in C

Published by

on

Introduction

➢File handing in C is the process in which we create, open, read, write, and close operations on a file.

➢C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.

Why do we need File Handling in C?

➢So far the operations using the C program are done on a prompt/terminal which is not stored anywhere.

➢The output is deleted when the program is closed.

➢But in the software industry, most programs are written to store the information fetched from the program.

➢The use of file handling is exactly what the situation calls for.

Features of file handling

Reusability:

➢The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high reusability.

Portability:

➢Without losing any data, files can be transferred to another in the computer system. The risk of flawed coding is minimized with this feature.

Efficient:

➢A large amount of input may be required for some programs. File handling allows you to easily access a part of a file using few instructions which saves a lot of time and reduces the chance of errors.

Storage Capacity:

➢Files allow you to store a large amount of data without having to worry about storing everything simultaneously in a program.

Types of File

➢A file can be classified into two types based on the way the file stores the data.

➢They are:

➢Text Files

Text Files

➢A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.

➢Each line in a text file ends with a new line character (‘\n’).

➢It can be read or written by any text editor.

➢They are generally stored with .txt file extension.

➢Text files can also be used to store the source code.

Binary Files

➢A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters.

➢They contain data that is stored in a similar manner to how it is stored in the main memory.

➢The binary files can be created only from within a program and their contents can only be read by a program.

➢More secure as they are not easily readable.

➢They are generally stored with .bin file extension.

C File Operations

➢C file operations refer to the different possible operations that we can perform on a file in C such as:

➢Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”

➢Opening an existing file – fopen()

➢Reading from file – fscanf() or fgets()

➢Writing to a file – fprintf() or fputs()

➢Moving to a specific location in a file – fseek(), rewind()

➢Closing a file – fclose()

File Pointer in C

➢A file pointer is a reference to a particular position in the opened file.

➢It is used in file handling to perform all file operations such as read, write, close, etc.

➢We use the FILE macro to declare the file pointer variable.

➢The FILE macro is defined inside <stdio.h> header file.

Syntax of File Pointer

◦FILE* pointer_name;

➢File Pointer is used in almost all the file operations in C.

Opening Data File

➢For opening a file in C, the fopen()function is used with the filename or file path along with the required access modes.

Syntax of fopen()

➢fopen(const char *file_name, const char *access_mode);

Parameters

file_namename of the file when present in the same directory as the source file. Otherwise, full path.

access_mode: Specifies for what operation the file is being opened.

Return Value

➢If the file is opened successfully, returns a file pointer to it.

➢If the file is not opened, then returns NULL.

File opening modes in C

ModeDescription
rSearches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
wOpen for reading in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
aSearches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
r+Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the first character in it. Returns NULL, if unable to open the file.

File opening modes in C

ModeDescription
w+Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open the file.
a+Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
rbOpen for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
wbOpen for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
abOpen for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.

File opening modes in C

ModeDescription
rb+Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
wb+Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
ab+Open for both reading and appending in binary mode. If the file does not exist, it will be created.

C Program to illustrate file opening

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE* fptr; fptr = fopen(“filename.txt”, “r”);

if (fptr == NULL) {

printf(“The file is not opened. The program will now exit.”);

exit(0);

}

return 0;

}

Create a File in C

➢The fopen() function can not only open a file but also can create a file if it does not exist already.

➢For that, we have to use the modes that allow the creation of a file if not found such as w, w+, wb, wb+, a, a+, ab, and ab+.

Example:

➢FILE *fptr;

➢fptr = fopen(“filename.txt”, “w”);

C Program to create a file

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE* fptr; fptr = fopen(“file.txt”, “w”);

if (fptr == NULL) {

printf(“The file is not opened. The program will exit now”);

exit(0);

}

else

printf(“The file is created Successfully.”);

return 0;

}

Closing Data File

➢The fclose() function is used to close the file.

➢After successful file operations, you must always close a file to remove it from the memory.

Syntax of fclose()

➢fclose(file_pointer);

➢where the file_pointer is the pointer to the opened file.

Example:

➢FILE *fptr ;

➢fptr= fopen(“fileName.txt”, “w”);

➢———- Some file Operations ——-

➢fclose(fptr);

Read Function

FunctionDescription
fscanf()Use formatted string and variable arguments list to take input from a file.
fgets()Input the whole line from the file.
fgetc()Reads a single character from the file.
fgetw()Reads a number from a file.
fread()Reads the specified bytes of data from a binary file.

➢The file read operation in C can be performed using functions fscanf() or fgets().

➢Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer.

➢There are also other functions we can use to read from a file.

➢So, it depends on you if you want to read the file line by line or character by character.

➢Such functions are listed below:

Example

FILE * fptr;

fptr = fopen(“fileName.txt”, “r”);

fscanf(fptr, “%s %s %s %d”, str1, str2, str3, &year); char c = fgetc(fptr);

➢The getc() and some other file reading functions return EOF (End Of File) when they reach the end of the file while reading.

➢EOF indicates the end of the file and its value is implementation-defined.

Note: One thing to note here is that after reading a particular part of the file, the file pointer will be automatically moved to the end of the last read character.

Write Function

➢The file write operations can be performed by the functions fprintf() and fputs() with similarities to read operations.

➢C programming also provides some other functions that can be used to write data to a file such as:

FunctionDescription
fprintf()Similar to printf(), this function use formatted string and varible arguments list to print output to the file.
fputs()Prints the whole line in the file and a newline at the end.
fputc()Prints a single character into the file.
fputw()Prints a number to the file.
fwrite()This functions write the specified amount of bytes to the binary file.

Example

FILE *fptr ;

fptr = fopen(“fileName.txt”, “w”);

fprintf(fptr, “%s %s %s %d”, “We”, “are”, “in”, 2012);

fputc(“a”, fptr);

String Input/Output Functions

➢Using string I/O functions fgets() and fputs(), data can be read from a file or written to a file in the form of array of characters.

fgets(): is used to read string from file.

Syntax: fgets(string, int_value, ptr_var);

➢Here, int_value denotes the no. of characters in the string.

fputs(): is used to write string to file.

Syntax: fputs(string, ptr_var);

Character Input/Output Functions

➢Using character I/O functions fgetc() and fputc(), data can be read from a file or written to a file one character at a time.

fgetc(): is used to read character from file.

Syntax: char_variable = fgetc(fp);.

fputc(): is used to write a character to file.

Syntax: fputc(character or character_variable, fp);

Formatted Input/Output Functions

➢Using formatted I/O functions, fprintf() and fscanf(), numbers, characters or string can be read from file or written onto file according to our requirement format.

fprintf(): is formatted output function which is used to write integer, float, char or string value to a file.

Syntax: fprintf(fp,”control_string”,list of variables);

fscanf(): is formatted input function which is used to read integer, float, char or string value from a file.

Syntax: fscanf(fp, “control_string”, &list_of_variables);

Example of fgetc()

 #include <stdio.h>

 int main() {

     FILE *fp = fopen(“file.txt”,”r”);

     if (fp == NULL)

       return 0;

     do {

         char c = fgetc(fp);

         if (feof(fp))

             break ;

         printf(“%c”, c);

     }while(1);

    fclose(fp);

    return(0);

}

Example of fputc()

 #include<stdio.h>

 int main() {

     int i = 0;

     FILE *fp = fopen(“output.txt”,”w”);

     if (fp == NULL)

       return 0;

     char string[] = “good bye”;

     for (i = 0; string[i]!=’\0′; i++)

         fputc(string[i], fp);

     fclose(fp);

fp = fopen(“output.txt”,”r”);

    fgets(string,20,fp);

    printf(“%s”,string);

    fclose(fp);

    return 0;

}

Example of fscanf()

 #include<stdio.h>  

 int main(){  

    FILE *fp;  

    char buff[255];//creating char array to store data of file  

    fp = fopen(“file.txt”, “r”);  

    while(fscanf(fp, “%s”, buff)!=EOF)  {  

    printf(“%s “, buff );  

    }  

    fclose(fp);  

    return 0;

 }  

Example of fputs() and fscanf()

 

 #include <stdio.h>

 #include <stdlib.h>

 int main () {

    char str1[10], str2[10], str3[10];

    int year;

    FILE * fp;

    fp = fopen (“file.txt”, “w+”);

    fputs(“We are in 2023”, fp);  

    rewind(fp);

fscanf(fp, “%s %s %s %d”, str1, str2, str3, &year);  

   printf(“Read String1 |%s|\n”, str1 );

   printf(“Read String2 |%s|\n”, str2 );

   printf(“Read String3 |%s|\n”, str3 );

   printf(“Read Integer |%d|\n”, year );

   fclose(fp);

   return(0);

}

Example of fgets()

 #include <stdio.h>

 int main(){

   char str[20];

   FILE *f = fopen(“emp.txt” , “r”);

   if(f == NULL){

     printf(“Error opening file”);

     return(-1);

   }

else{

    fgets(str, 20, f);

//str= pointer to an initialized string in which characters are copied

//20 = number of characters to copy

//f = pointer to the file stream

printf(“%s”,str);

  } 

  fclose(f);  

  return(0);

}

WAP to write some text in “Welcome to BCA program” in a file test.txt?

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *fptr; fptr = fopen(“test.txt”, “w”);

if (fptr == NULL) {

printf(“Error!”);

exit(0);

}

fprintf(fptr, “%s”, “Wel come to BCA Program”);

fclose(fptr);

return 0;

}

WAP to copy the contents of a student.txt file into another file called info.txt.

 #include <stdio.h>

 #include <stdlib.h> 

 int main() {

     FILE *fptr1, *fptr2;

     char filename[100], c; 

     fptr1 = fopen(“student.txt”, “r”);

     if (fptr1 == NULL) {

         printf(“Cannot open file”);

         exit(0);

     }

     fptr2 = fopen(“info.txt”, “w”);

if (fptr2 == NULL) {

        printf(“Cannot open file”);

        exit(0);

    }   

    c = fgetc(fptr1);

    while (c != EOF) {

        fputc(c, fptr2);

        c = fgetc(fptr1);

    } 

    printf(“\nContents copied”); 

    fclose(fptr1);

    fclose(fptr2);

    return 0;

}

Delete a file

➢The remove() function in C/C++ can be used to delete a file.

➢The function returns 0 if the file is deleted successfully, ➢Otherwise, it returns a non-zero value.

➢The remove() is defined inside the <stdio.h>header file.

Syntax of remove()

➢remove(“filename”);

Parameters

➢This function takes a string as a parameter, which represents the name of the file to be deleted.

Return Value

➢The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value.

Example of remove()

#include <stdio.h>

int main() {

if (remove(“abc.txt”) == 0)

printf(“Deleted successfully”);

else

printf(“Unable to delete the file”);

return 0;

}

Random Accessing Files

➢Random access file in C enables us to read or write any data in our disk file without reading or writing every piece of data before it.

➢In a random-access file, we may quickly search for data, edit it or even remove it.

➢We can open and close random access files in C, same as sequential files with the same opening mode, but we need a few new functions to access files randomly.

➢This extra effort pays off flexibility, power, and disk access speed. Random access to a file in C is carried with the help of functions like:

➢ftell()

➢fseek()

➢rewind()

ftell in C

➢In C, the function ftell() is used to determine the file pointer’s location relative to the file’s beginning. ftell() has the following syntax:

➢pos = ftell(FILE *fp);

➢Where fp is a file pointer and pos holds the current position i.e., total bytes read (or written).

➢For Example: If a file has 20 bytes of data and if the ftell() function returns 5 it means that 5 bytes have already been read (or written).

C program to demonstrate ftell.

 #include <stdio.h>

 int main() {

    FILE *filePointer;

    filePointer = fopen(“test.txt”, “r”);

    printf(“The current location of file pointer is %d bytes from the start of the file\n”, ftell(filePointer));

    fseek(filePointer, 4, SEEK_SET);

    printf(“The current location of file pointer is %d bytes from the start of the file\n”, ftell(filePointer));

     fclose(filePointer);

    return 0;

 }

Rewind in C

➢The file pointer is moved to the beginning of the file using this function.

➢It comes in handy when we need to update a file.

➢The following is the syntax: ➢rewind(FILE *fp);

➢Here, fp is a file pointer of type FILE.

C program to understand the rewind() function.

 #include<stdio.h>

 int main() {

     FILE *fp;

     char ch;

     fp = fopen(“myfile.txt”,”r”);

     if(fp == NULL)  {

         printf(“Error in opening file\n”);

         return 0;

     }

     printf(“Position of the pointer : %ld\n”,ftell(fp));   

while((ch = fgetc(fp))!=EOF) {

        printf(“%c”,ch);

    }

    printf(“\nPosition of the pointer : %ld\n”,ftell(fp));

    rewind(fp);

    printf(“Position of the pointer : %ld\n”,ftell(fp));   

    fclose(fp);

    return 0;

}

fseek in C

➢The function fseek() is a standard library function in C language, present in stdio.h header file.

➢It is used to move or change the position of the file pointer which is being used to read the file, to a specified offset position.

Syntax of fseek() in C

➢fseek(FILE *filePointer, long offset, int origin);

➢Where,

filePointer : pointer to the FILE object that identifies the stream, which we have to modify.

offset : number of bytes to shift the position of the FILE pointer, relative to its current origin to determine the new position.

origin : determines the current position of the FILE pointer from where the offset needs to be added ie. it indicates the contemporary position of the file pointer from where the specified offset value will be added, in order to move the position of the file pointer using the fseek() function.

fseek in C

➢The parameter origin can have the following three values

SEEK_END : denotes the end of the file

SEEK_SET : denotes the starting of the file

SEEK_CUR : denotes the current position of the file pointer.

Example of fseek()

 #include <stdio.h> 

 void main(){ 

    FILE *fp;  

    fp = fopen(“myfile.txt”,”w+”); 

    fputs(“This is javatpoint”, fp);      

    fseek( fp, 8, SEEK_SET );  

    fputs(“Rajesh Hamal”, fp); 

    fclose(fp); 

 }

Some text file is given, create another tet file replacing the following words “Apple”  to “Football” and “Banana” to “Basketball”.

 #include<stdio.h>

 #include<string.h>>

 int main() {

     FILE *fp, *fpp;

     fp = fopen(“myfile.txt”,”r”);

     if(fp == NULL)  {

         printf(“Error in opening file\n”);

         return 0;

     }

     fpp = fopen(“update_file.txt”,”w”);

     if(fpp == NULL)  {

         printf(“Error in opening file\n”);

         return 0;  

   }

char c[15];

    while(fscanf(fp,”%s”,&c)!=EOF) {

        if(strcmp(c,”Apple”)==0)

           fprintf(fpp,”Football”,c);

        else if(strcmp(c,”Banana”)==0)

           fprintf(fpp,”Basketball”,c);

        else

            fprintf(fpp,”%s “,c);

    }

    fclose(fp);

    fclose(fpp);

    return 0;

}

WAP to accept 100 numbers from user and store them in odd.txt file(if number is odd) or even.txt(if number is even) then display odd numbers reading from odd.txt file.

 #include<stdio.h>

 void main() {

  int num, i =0;

  FILE *po, *pe;

  po = fopen(“odd.txt”,”w”);

  pe = fopen(“even.txt”,”w”);

  if(po==NULL) {

   printf(“Something went wrong!”);

  }

  if(pe==NULL)  {

   printf(“Something went wrong!”);

  }

do {

  printf(“Enter number:\n”);

  scanf(“%d”,&num);

  if(num%2!=0)  {

   fprintf(po,”%d\t”,num);

  }

  else  {

   fprintf(pe,”%d\t”,num);

  }

  i++;

 }while(i != 100);

 fclose(pe);

 fclose(po);

 po = fopen(“odd.txt”,”r”);

  printf(“\nContent read from odd.txt:\n”);

  while(!feof(po)) {

   fscanf(po,”%d\t”,&num);

   printf(“%d\t”, num);

  }

  fclose(po);

 }

Exercise

➢Write a program to create a file called emp.txt and store information about a person, in terms of his name, age and salary.

➢Write a Program to print contents of file.

➢Write a Program to merge contents of two files into a third file

➢WAP to find the size of a given file student.txt

➢WAP to count the number of vowels, digits, spaces, and lines in a file and display the content on screen.

➢Given a text file, create another text file deleting the following words “three”, “two” and “one”.

If you need this question answered which is given in the exercise then plz contact me on this site;https://www.facebook.com/thapabikram.prabesh

Leave a Reply

About the blog

Programming is a essential part of life. It helps to gain knowledge about different program and make computer expertise.

Newsletter

Subscribe to my email newsletter full of inspiring stories about my journey that continues.

No comments:

Post a Comment

Research in Social Science

   C  Concept of Research in Social Science -         Understanding the concept of Research Methods, Techniques and Tools: Interview, Fo...