File Handle

# include <stdio.h>

int main() {

    char name[50], address[100], phone[20];

    FILE *fp;

    fp = fopen("contacts.txt", "w");

    if (fp == NULL) {

        printf("Error: could not create file.\n");

        return 1;

    }

    printf("Enter name: ");

    fgets(name, 50, stdin);

    printf("Enter address: ");

    fgets(address, 100, stdin);

    printf("Enter phone number: ");

    fgets(phone, 20, stdin);

    fprintf(fp, "Name: %sAddress: %sPhone: %s", name, address, phone);

    fclose(fp);

    printf("File created successfully.\n");

    return 0;

}

 

 

 

2.      Write a c program to add some more records in above file.

#include <stdio.h>

int main() {

    char name[50], address[100], phone[20];

    FILE *fp;

    fp = fopen("contacts.txt", "a");

    if (fp == NULL) {

        printf("Error: could not open file.\n");

        return 1;

    }

    printf("Enter name: ");

    fgets(name, 50, stdin);

    printf("Enter address: ");

    fgets(address, 100, stdin);

    printf("Enter phone number: ");

    fgets(phone, 20, stdin);

    fprintf(fp, "Name: %sAddress: %sPhone: %s", name, address, phone);

    fclose(fp);

    printf("Record added successfully.\n");

    return 0;

}

 

3.      Write a program to display those records

#include <stdio.h>

int main() {

    char line[200];

    FILE *fp;

    fp = fopen("contacts.txt", "r");

    if (fp == NULL) {

        printf("Error: could not open file.\n");

        return 1;

    }

    while (fgets(line, 200, fp) != NULL) {

        printf("%s", line);

    }

    fclose(fp);

    return 0;

}

 

 

 

# include <stdio.h>

int main() {

    int i;

                char name[50], address[100], phone[20];

    FILE *fp;

    fp = fopen("contacts.txt", "a");

    if (fp == NULL) {

        printf("Error: could not create file.\n");

        return 1;

    }

    for(i=1;i<=10;i++)

    {

    printf("Enter name: ");

    fgets(name, 50, stdin);

    printf("Enter address: ");

    fgets(address, 100, stdin);

    printf("Enter phone number: ");

    fgets(phone, 20, stdin);

    fprintf(fp, "Name: %sAddress: %sPhone: %s", name, address, phone);

}

    fclose(fp);

    printf("File created successfully.\n");

    return 0;

}

 

 

Working with Files

Creation of the new file

Opening an existing file

Reading from the file

Writing to the file

Deleting the file

 

SN       Function          Description

1.         fopen()             opens new or existing file

2.         fprintf()            write data into the file

3.         fscanf()            reads data from the file

4.         fputc()              writes a character into the file

5.         fgetc()              reads a character from file

6.         fclose()            closes the file

7.         fseek()             sets the file pointer to given position

8.         fputw()             writes an integer to file

9.         fgetw()             reads an integer from file

10.       ftell()                returns current position

11.       rewind()           sets the file pointer to the beginning of the file

Different Modes in file handling

w : Opens for writing

w+ : Opens for writing and reading (pointer at the beginning)

r : Opens for reading

r+ : Opens for reading and writing. (file must be there, pointer at the beginning)

a : Opens for writing (pointer at the end)

a+ : Opens for writing and reading (pointer at the end)

 

 

Binary

rb           

                Open for reading in binary mode.            

                If the file does not exist, fopen() returns NULL.

wb         

                Open for 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 append in binary mode. Data is added to the end of the file.     

                If the file does not exist, it will be created.

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.

 

Types of Files:

1.    Text files

The text files are the most basic/simplest types of files that a user can create in a C program. We create the text files using an extension .txt with the help of a simple text editor. In general, we can use notepads for the creation of .txt files. These files store info internally in ASCII character format, but when we open these files, the content/text opens in a human-readable form.

2. Binary files

The binary files store info and data in the binary format of 0’s and 1’s (the binary number system). Thus, the files occupy comparatively lesser space in the storage. In simpler words, the binary files store data and info the same way a computer holds the info in its memory. Thus, it can be accessed very easily as compared to a text file.

 

Depending up on the method of accessing the data stored, there are two types of files.

1. Sequential file

A sequential file is a type of file structure used in computer systems to organize and store data in a sequential order. In a sequential file, records are stored one after another, with each new record being appended to the end of the file. This means that the records are stored in the order they are added, and accessing the data follows a sequential pattern from the beginning to the end of the file.

In a sequential file, the records have a fixed length or are variable-length with a marker indicating the end of each record. When reading or writing data in a sequential file, the file pointer moves sequentially through the file, starting from the first record and progressing through each subsequent record.

2. Random access file

A random access file is a type of file structure that allows direct access to any record within the file, enabling efficient searching, updating, and retrieval of individual records. Unlike sequential access files where data is organized and accessed sequentially, random access files provide the ability to access records in any order based on their position or key.

In a random access file, records are stored with a unique identifier or a specific position within the file. This identifier or position allows for direct access to a particular record without the need to traverse through the entire file. The file system maintains an index or data structure that facilitates efficient retrieval of records based on their identifiers or positions.

Creating a file pointer

When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and the program.

FILE *fptr;

Opening a file - for creation and edit

Opening a file is performed using the fopen() function defined in the stdio.h header file.

The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

For example

fopen("E:\\cprogram\\newprogram.txt","w");

 

Closing a File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);

 

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.

 

Writing data on a data file in C

After we open data in writing mode, if we need to store data in a data file then, this can be done by using ‘fprintf’ keyword and more. For writing data file must be opened in writing mode i.e. ‘w’. While opening data file in ‘w’ mode, If the file already exists its contents will be erased and new are stored. If the file doesn't exist then it will be created.

 

Writing data on a data file in C

Syntax to write data on data file

fprintf (filepointer_variable, “list of format specifier”, list of variables);

If we want to store data in book id, book name and its price in data file named “library.txt” then

fprintf (fptr, “%d %s %f”, id, name, price);

[Note: As ‘printf’ does not has ‘&’ in its variable list, ‘fprintf’ also doesn’t use ‘&’ ]

 

Program example

#include <conio.h>

#include <stdio.h>

int main()

{

   char name[10];

   float price;

   int id;

   FILE *fptr;

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

   printf("Enter book id name and price”);

   scanf(“%d %s %f”, &id, name ,&price); // stores id name and price in main memory

   fprintf(fptr,“%d %s %f”,id, name ,price); // stores id name and price in secondary memory

   fclose(fptr);

   return 0;

}

 

 

Read and display single records in C

#include <stdio.h>

#include <conio.h>

int main()

{

   char n[10],p[10];

   float s;

   FILE *fptr;

   fptr = fopen("employee.txt”,”r”);

   fscanf(fptr,"%s %s %f \n",n, p, &s);

   printf("%s %s %f",n, p, s);

   fclose(fptr);

   return 0;

}

 

Read and Display all records in C

#include <stdio.h>

#include <conio.h>

int main()

{

   char n[10],p[10];

   float s;

   FILE *fptr;

   fptr = fopen("employee.txt”,”r”);

   while (fscanf(fptr,"%s %s %f \n",n, p, &s) != EOF)

   {

     printf("%s %s %f",n, p, s);

   }

   fclose(fptr);

   return 0;

}

 

Display only those records whose salary is greater than 50000. 

#include <stdio.h>

#include <conio.h>

int main()

{

   char n[10],p[10];

   float s;

   FILE *fptr;

   fptr = fopen("employee.txt”,”r”);

   while (fscanf(fptr,"%s %s %f \n",n, p, &s) != EOF)

   {

    if (s>50000)

   {

     printf("%s %s %f",n, p, s);

   }

   }

   fclose(fptr);

   return 0;

}

 

Read and Display records all records whose name starts with “S” in C.

#include <stdio.h>

#include <conio.h>

#include <string.h>

int main()

{

   char n[10],p[10];

   float s;

   FILE *fptr;

   fptr = fopen("employee.txt”,”r”);

   while (fscanf(fptr,"%s %s %f \n",n, p, &s) != EOF)

   {

    if (strcmp(toupper(n[0]), ’S’) == 0 )

   {

     printf("%s %s %f",n, p, s);

   }

   }

   fclose(fptr);

   return 0;

}

 

 

Program example

 

#include

int main()

{

   char name[10];

   float price;

   int id;

   FILE *fptr;

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

   printf("Enter book id name and price”);

   scanf(“%d %s %f”, &id, name ,&price); // stores id name and price in main memory

   fprintf(fptr,“%d %s %f”,id, name ,price); // stores id name and price in secondary memory

   fclose(fptr);

   return 0;

}

The above program stores only one set of records. We need to change the program structure if we want to stores multiples data in data file. Let us say 100 records, N records, Until user press ‘Y’ and as per user requirements. Click here.

 

Reading data from a data file in C

After we open data in writing mode, if we need to read and display data from a data file then, this can be done by using ‘fscanf’ keyword and more.

 

Syntax to write data on data file

 

fscanf (filepointer_variable, “list of format specifier”, list of variables);

This can be used in our program as:

If we want to read and display book id, book name and its price from a data file named “library.txt” then

 

fscanf (fptr, “%d %s %f”, &id, name, &price);

[Note: As in ‘scanf’ we use ‘&’ in ‘int’ and ‘float’ but not in ‘char’ similarly in ‘fscanf’ also we do same.]

 

EOF in C

Suppose, you want to display all the books whose price is greater then 500. While displaying, we do not know the exact number of records in the data file to be accessed. So, to overcome that we use EOF (End of file). It is used in program while reading the content back from the file. After the detection of EOF character by the C compiler the reading of the file stops. So, it is used to represent the end state of the file while reading back the content.

 

Program example

 

#include

int main()

{

   char name[10];

   float price;

   int id;

   FILE *fptr;

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

   printf(“Book id \t Book name \t Book Price”); // This will be a heading for our displayed record

   while ( fscanf (fptr, “%d %s %f”, “&id, name, &price”) != EOF )

  {

 printf(“%d %s %f”, id, name ,price);

}

   fclose(fptr);

   return 0;

}

The above program displays all the records from the data file ‘record.txt’. if We need to change the program structure if we want display specific records based on conditions then, Let us whose salary is greater than 500, who lives in ‘London’ etc. Click here.

 

Adding data on a data file (Append)

Append means adding data in existing data file, it is similar to writing or storing data in data file. Same ‘fprintf’ keyword is used to add data. The only difference is we open our data file in append mode i.e. ‘a’. This allows user to add record at the end of the existing records in a data file. If there is no existing data file with the mentioned name then new will be created and records are stored from the beginning of the file.

 

Program example to add one record in existing data file “library.txt”

#include

int main()

{

   char name[10];

   float price;

   int id;

   FILE *fptr;

   fptr = fopen(“library.txt” , ”a”); // opens data file in append mode

   printf("Enter book id name and price”);

   scanf(“%d %s %f”, &id, name ,&price); // stores id name and price in main memory

   fprintf(fptr,“%d %s %f”,id, name ,price); // stores id name and price in secondary memory

   fclose(fptr);

   return 0;

}

The above program stores only add one record at the end of the existing data file “library.txt”.

 

 

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

 

Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

·         Address of data to be written in the disk

·         Size of data to be written in the disk

·         Number of such type of data

·         Pointer to the file where you want to write.

fwrite(addressData, sizeData, numbersData, pointerToFile);

 

Write to a binary file using fwrite()

#include <stdio.h>

#include <stdlib.h>

struct threeNum

{

   int n1, n2, n3;

};

int main()

{

   int n;

   struct threeNum num;

   FILE *fptr;

   if ((fptr = fopen("C:\\program.bin","wb")) == NULL){

       printf("Error! opening file");

      // Program exits if the file pointer returns NULL.

       exit(1);

   }

   for(n = 1; n < 5; ++n)

   {

      num.n1 = n;

      num.n2 = 5*n;

      num.n3 = 5*n + 1;

      fwrite(&num, sizeof(struct threeNum), 1, fptr);

   }

   fclose(fptr);

return 0;

}

 

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

fread(addressData, sizeData, numbersData, pointerToFile);

 

Read from a binary file using fread()

#include <stdio.h>

#include <stdlib.h>

 

struct threeNum

{

   int n1, n2, n3;

};

 

int main()

{

   int n;

   struct threeNum num;

   FILE *fptr;

 

   if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

       printf("Error! opening file");

 

       // Program exits if the file pointer returns NULL.

       exit(1);

   }

 

   for(n = 1; n < 5; ++n)

   {

      fread(&num, sizeof(struct threeNum), 1, fptr);

      printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

   }

   fclose(fptr);

 

   return 0;

}

 

Getting data using fseek()

If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()

fseek(FILE * stream, long int offset, int whence);

 

The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.

 

Different whence in fseek()

Whence               Meaning

SEEK_SET             Starts the offset from the beginning of the file.

SEEK_END           Starts the offset from the end of the file.

SEEK_CUR           Starts the offset from the current location of the cursor in the file.

 

Reading the records from the file program.bin in the reverse order (last to first) and prints it.

#include <stdio.h>

#include <stdlib.h>

struct threeNum

{

   int n1, n2, n3;

};

int main()

{

   int n;

   struct threeNum num;

   FILE *fptr;

 

   if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.

       exit(1);

   }

      // Moves the cursor to the end of the file

   fseek(fptr, -sizeof(struct threeNum), SEEK_END);

 

   for(n = 1; n < 5; ++n)

   {

      fread(&num, sizeof(struct threeNum), 1, fptr);

      printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

      fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);

   }

   fclose(fptr);

   return 0;

}

 

 

 


Comments

Popular posts from this blog

Question Collection-11

Important Questions for XII