Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

File Input/Output in C programming

October 18, 2013 Posted by: GPA Views: 26226 0 comments

C compiler has many functions for reading data from files and for writing data to files. For example fgetc reads one character from a file. Function fputc writes one character to a file. In this article we'll use FILE structure. Each file must have pointer of type FILE that is used to get functions to read file and write to the file. To open file we must use function fopen. It takes two arguments:
first - a file name and second - a file open mode. About all mode you can read in table below. To determine whether the end of file use function feof.

 

ModeExplanation
r Open the file for reading.
w Open and create file for writing.
a
Allow append information to the end of the file.
r+
Open the file for reading and writing.
w+ If the file already exists, remove the file contents.
a+
Open or create a file for edit. Allow append information to the end of the file.
rb
Open and read the file in binary mode.
wb
Create a new file for writing in binary mode.
ab
Allow append information to the end of the file in binary mode.
rb+
Open the file for reading and writing in binary mode.
wb+
If the file already exists, remove the file contents in binary mode.
ab+
Open or create a file for edit. Allow append information to the end of the file in binary mode.

To show how you can use these functions and modes let's solve these exercises:

Exercise I

Write a C program that reads personal information from a file. Write a program that will read in information on a person stored in a text file in a delimited format. The records will have the following format:

 NAME|PHONE NUMBER|ADDRESS|CITY|STATE|ZIP

Read each record into a structure. The structure should contain fields of the appropriate type for the data. That is, the zip field should be an integer, the other fields should be the char * s. Use the strtok function to break the lines into the appropriate fields. Store the structures in an array.

Exercise II

Modify the above program so that it will convert the text file format into a binary format. That is, after you have read the data into your structures, write the data out to a binary file, and then read it in and display it.




#include <stdio.h>
#include <stdlib.h>
 
//Structure of person
struct Person {
   char* NAME;
   char* PHONENUMBER;
   char* ADDRESS;
   char* CITY;
   char* STATE;
   int ZIP;
};
//Prototype of functions
void read_data_from_txt_file(char* filename);
void write_To_Binary_File(struct Person person[],int numberofPersons);
void read_from_binary_file(int numberofPersons);
 
//main function
int main(int argc, char *argv[])
{
  read_data_from_txt_file("Persons.txt");//call function read data from txt file
  system("PAUSE");	
  return 0;
}
 
void read_data_from_txt_file(char* filename ){
    int numberofrecords=0;
    FILE *f = fopen(filename, "rb");//read file
    if (f == NULL) {
    fprintf(stderr, "Can't open input file!\n");
       return;
    }
    fseek(f, 0, SEEK_END);
    long pos = ftell(f);
    fseek(f, 0, SEEK_SET);
    char *bytes = malloc(pos+1); /* include an extra byte incase file isn't '\n' terminated */
    fread(bytes, pos, 1, f);
    if (bytes[pos-1]!='\n')
    {
        bytes[pos++] = '\n';
    }
    long i;
    long length = 0;
    int counter = 0;
    size_t size=100;
    char** data=malloc(size*sizeof(char*));
    data[0]=bytes;
    for(i=0; i<pos; i++)
    {
        if (bytes[i]=='\n') {
            bytes[i]='\0';
            counter++;
            if (counter>=size) {
                size+=100;
                data=realloc(data,size*sizeof(char*));
                if (data==NULL) {
                    fprintf(stderr,"Couldn't allocate enough memory!\n");
                    exit(1);
                }
            }
            numberofrecords++;//number of lines
            data[counter]=&bytes[i+1];
            length = data[counter] - data[counter - 1] - 1;
        }
 
    }
    //create struct of person
    struct Person p[100];
    char * fileLine;
    for (i=0;i<numberofrecords;i++){
      fileLine = strtok(data[i],"|"); //read data from file using function strtok 
      int k=0;
      char* strin="";
      //split string using delimiter "|"
      while (fileLine != NULL)
        {
            //read data from file using function strtok 
           if(k==0){
             p[i].NAME=fileLine;
           }
           if(k==1){
             p[i].PHONENUMBER=fileLine;
           }
           if(k==2){
             p[i].ADDRESS=fileLine;
           }
           if(k==3){
             p[i].CITY=fileLine;
           }
           if(k==4){
             p[i].STATE=fileLine;
           }
           if(k==5){
             p[i].ZIP=atoi(fileLine);
           }
           k++;
           fileLine = strtok (NULL, "|");
 
        }
    }
    printf("Read data from txt file\n");
    //Show results
    printf("NAME\tPHONENUMBER\tADDRESS\tCITY\tSTATE\tZIP\n\n");
    for(i=0;i<numberofrecords;i++){
        printf("%s\t%s\t%s\t%s\t%s\t%d\n",p[i].NAME,p[i].PHONENUMBER,p[i].ADDRESS,p[i].CITY,p[i].STATE,p[i].ZIP);
    }
 
    //Call function to write to binary file
    write_To_Binary_File(p,numberofrecords);
    //Call function ReadFromFile
    read_from_binary_file(numberofrecords);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////FOR Exercise II/////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void write_To_Binary_File(struct Person person[],int nPersons){
        int j=0;
		FILE *binaryfile;
		binaryfile=fopen("Persons.bin","wb");
		if (!binaryfile)
		{
			printf("Unable to open file!");
			return 1;
		}
		for (j=0;j< nPersons;j++)
		{
			fwrite(&person[j], sizeof(struct Person), 1, binaryfile);//Write to binary file
		}
		fclose(binaryfile);   //close file
}
//Read From Binary File
void read_from_binary_file(int nPersons){
 
		FILE *binaryfile;
		struct Person person[100];
 
		binaryfile=fopen("Persons.bin","rb");
		if (!binaryfile)
		{
			printf("Unable to open file!");
			return 1;
		}
		printf("\n\nRead data from binary file\n");
		printf("NAME\tPHONENUMBER\tADDRESS\tCITY\tSTATE\tZIP\n\n");
        int i;
        for (i=0; i <nPersons; i++)
		{
            //Read from binary file
			 fread(&person[i],sizeof(struct Person),1,binaryfile);
			 //show result
             printf("%s\t%s\t%s\t%s\t%s\t%d\n",person[i].NAME,person[i].PHONENUMBER,person[i].ADDRESS,person[i].CITY,person[i].STATE,person[i].ZIP);
		}
		fclose(binaryfile);  
 
}   


Output

File Input Output in C programming

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe