SlideShare a Scribd company logo
1 of 17
typedef – to define new datatype                                   bitfieds

    ‘ typedef ’ is a keyword,which allows you to   struct playcard {
specify a new name for a datatype which is            unsigned pips ;
already defined in c language program.                unsigned suit ;
Syntax:                                            };
    typedef <datatype> <newname>                         Above structure occupies 4 bytes of
   /* Re-defining int type as Integer type */      memory. But the member pips accepts a
typedef int Integer;                               value between 1 to 13 and the member suit
int main( ) {                                      accepts any value of 0, 1, 2 and 3 .
    Interger a ,b , sub;                                    So we can create a more packed
    a = 20,b = 10;                                 representation of above structure with bitfields.
    sub = a - b;                                   struct playcard {
    printf(“%d - %d = %d”, a, b, sub);                unsigned pips : 4;
}                                                     unsigned suit : 2;
 /* Defining structure with typedef to avoid       };
   repeated usage of struct keyword */                A bitfield is a set of adjacent bits within
                                                   a single machine word.
typedef struct {                                       4-bit field called pips that is capable of
  int hours;                                       storing the 16 values 0 to 15, and a 2-bit
  int minutes;                                     field called suit that is capable of storing
} TIME ;                                           values 0, 1, 2, and 3. So the entire structure
int main( ) {                                      variable occupies only one byte.
   TIME t1, t2 , *t;                               Note : arrays of bit fields and a pointer to
   t = (TIME *) calloc (10, sizeof( TIME ));       address a bit field is not permitted.
}
Enumeration – a set of named integers, makes program more readable
  Declaration of enumeration :
    enum <enum_name> { member1, member2, …. …. …. } ;
  Example :
    enum option { YES, NO, CANCEL } ;
    By default YES has value 0, NO has value 1 and CANCEL has 2.
    enum direction { EAST = 1, SOUTH, WEST = 6, NORTH } ;
    Now EAST has value 1, SOUTH has value 2, WEST has value 6, and NORTH has value 7.
    Enumerated types can be converted implicitly or cast explicitly.
    int x = WEST ; /* Valid. x contains 6. */
    enum direction y ; y = (enum direction ) 2 ;    /* Valid. Y contains SOUTH */

#include<stdio.h>                                #include<stdio.h>
int main() {                                     enum color {RED = 1,ORANGE,GREEN };
    int signal;                                  int main() {
    printf ("ttt MENU nt1.RED n");             enum color signal;
    printf ("t2.ORANGEnt3.GREEN n“ );            printf ("ttt MENU nt1.RED n");
    printf ("nt Enter the signal : “ );            printf ("t2.ORANGEnt3.GREENn");
    scanf (“%d”, &signal );                          printf ("nt Enter the signal : ");
    switch(signal)                                   scanf ("%d", &signal);
    {                                                switch(signal) {
       case 1:                                         case RED:
         printf(“t Stop and Wait!"); break;             printf("t Stop and Wait!"); break;
       case 2:                                         case ORANGE:
         printf(“t Ready to start!"); break;            printf("t Ready to start!"); break;
       case 3:                                         case GREEN:
         printf(“t Start and go!"); break;              printf("t Start and go!"); break;
    }                                                }
}                                                }
Console I / O Vs File I / O
 scanf( ) and printf( ) functions read and write data which always uses the
  terminal (keyboard and screen) as the target.
 It becomes confusing and time consuming to use large volumes of data
  through terminals.
 The entire data is lost when either program terminates or computer is
  turned off.
 Some times it may be necessary to store data in a manner that can be
  later retrieved and processed.
       This leads to employ the concept of FILES to store data permanently
  in the system.

                                                           File Operations
       Record is logical group of data fields that
comprise a single row of information, which          1. Creating a new file
describes the characteristics of an object.          2. Opening an existing file
     File is a set of records that can be accessed   3. Reading from a file
through the set of library functions.                4. Writing to a file
      A File is a place on disk where a group of     5. Moving to a specific
related data ( records ) can be stored                  location in a file (seek)
                                                     6. Closing a file
A Stream acts as an interface between a program
                                                   and an input/output Device.

    Stream is a Sequence of data bytes, which is used to read and write data to a file.
   The streams that represent the input data of a program are known as Input Streams, where
as the streams that represent the output data of a program are known as Output Streams.
   Input streams gets the data from different input devices such as keyboard and mouse and
provide input data to the program.
    Output Streams obtain data from the program and write that on different Output Devices
such as Memory or print them on the Screen.

                                                Types of Files
1.Text file : It can be thought of as a stream of characters that can be processed sequentially
and in forward direction only.
2.Binary file : It is collection of bytes like images.
3.Sequential File: Data stored sequentially, to read the last record of the file, we need to
traverse all the previous records before it. Ex: files on magnetic tapes.
4.Random Access File: Data can be accessed and modified randomly. We can read any record
directly. Ex : files on disks.
Steps involved using files

/*program to write and read data from file*/        1. Declaring FILE pointer variable :
#include<stdio.h>                                   Syntax :
void main() {                                         FILE *file_pointer1;
   FILE *fp;
   char ch;                                         2. Open a file using fopen() function :
   fp = fopen(“data.txt”, “w”);                     Syntax :
   if(fp == NULL) {                                  fp= fopen(“filename”,“mode of access”);
       printf(“Cannot open file.”);
       exit(0);                                     3. fputc() – Used to write a character to
    }                                               the file.
    printf(“Type text ( to stop press ‘.’ ) : ”);   Syntax :
    while(ch != ‘.’) {                                 fputc(character, file_pointer);
       ch = getche();
       fputc(ch,fp);                                4. fgetc() – Used to read a character to the
     }                                              file.
     fclose(fp);                                    Syntax :
     printf(“nContants read : “);                     fgetc(file_pointer);
     fp = fopen(“data.txt”,”r”);
     while(!feof(fp))                               5. Close a file using fclose() function :
       printf(“%d”, fgetc(fp));                     Syntax :
    fclose(fp);                                        fclose(file_pointer);
}
/* creating a new file */                         file pointer used to handle files
int main(){
   char ch;FILE *fp;                                filepointer=fopen(“filename”,”mode”);
   printf("nEnter the textn");
   printf("nt(Press ctrl+Z after
                    completing text)n");                   putc(character,filepointer);
   fp=fopen("str.txt","w");
   while((ch=getchar())!=EOF)                                fclose(filepointer);
       putc(ch,fp);
   fclose(fp);
}


 /* Reading the contents of existing file */   /* appending data to an existing file */
 #include<stdio.h>                             int main() {
 int main() {                                     FILE *fp; char ch;
    FILE *fp;                                     printf("nEnter the textn");
    char ch;                                      printf("nt(Press ctrl+Z after
    fp=fopen("str.txt","r");                                  completing text)n");
    while((ch=getc(fp))!=EOF)                     fp=fopen("str.txt","a");
       printf("%c",ch);                           while((ch=getchar())!=EOF)
    fclose(fp);                                          putc(ch,fp);
 }                                                fclose(fp);
                                               }
r -- open a file in read mode                     r+ -- open a file in read and write mode
  -- if file exits, the marker is positioned at      -- if file exits, the marker is positioned
       beginning.                                       at beginning.
  -- if file does not exist, error returned.         -- if file does not exist, NULL returned.
w -- open a file in write mode                    w+ -- open a file in read and write mode
  -- if file exits, all its data is erased.          -- if file exits, all its data is erased.
  -- if file does not exist, it is created.          -- if file does not exist, it is created.
a -- open a file in append mode                   a+ -- open a file in read and append mode
  -- if file exits, the marker is positioned         -- if file exits, the marker is positioned
     at end.                                             at end.
  -- if file does not exist, it is created.          -- if file does not exist, it is created.

            rb , wb , ab, rb+ , wb+ , ab+ are modes to operate a file as binary file.

int main( ) { /* Without using w+ */                /* open a file in read and write mode */
   FILE *fp; char ch;                             int main( ) {
   printf("nEnter the textn");                     FILE *fp; char ch;
   fp=fopen("str1.txt","w");                         printf("nEnter the textn");
   while((ch=getchar())!='n‘)putc(ch,fp);           fp=fopen("str1.txt","w+");
   fclose(fp);                                       while((ch=getchar())!='n') putc(ch,fp);
   fp=fopen("str1.txt","r");                         rewind(fp);
   while((ch=getc(fp))!=EOF)                         while((ch=getc(fp))!=EOF)
     printf("%c",ch);                                  printf("%c",ch);
   fclose(fp);                                       fclose(fp);
}                                                 }
File Input / Output Functions
fopen(fp, mode)   Open existing file / Create new file
fclose(fp)        Closes a file associated with file pointer.
closeall ( )      Closes all opened files with fopen()
fgetc(ch, fp)     Reads character from current position and advances the pointer to
                  next character.
fprintf( )        Writes all types of data values to the file.
fscanf()          Reads all types of data values from a file.
gets()            Reads string from a file.
puts()            Writes string to a file.
getw()            Reads integer from a file.
putw()            Writes integer to a file.
fread()           Reads structured data written by fwrite() function
fwrite()          Writes block of structured data to the file.
fseek()           Sets the pointer position anywhere in the file
feof()            Detects the end of file.
rewind()          Sets the record pointer at the beginning of the file.
ferror()          Reports error occurred while read/write operations
fflush()          Clears buffer of input stream and writes buffer of output stream.
ftell()           Returns the current pointer position.
Text files Vs Binary Files

/* Copying one binary file to other */      “rb”    open a file in read mode
                                            “wb”  open a file in write mode
#include<stdio.h>
int main( )                                 “ab”    open a file in append mode
{                                           “rb+”  open a pre-existing file in read and
  FILE *fs,*ft;                             write mode
  char ch;                                  “wb+” open a file in read and write mode
  fs=fopen("pr1.exe","rb");
  if(fs==NULL){                             “ab+”  open a file in read and append mode
     printf("nCannot Open the file");      Text File :
     exit(0);                               i) Data are human readable characters.
  }                                         ii) Each line ends with a newline character.
  ft=fopen("newpr1.exe","wb");              iii) Ctrl+z or Ctrl+d is end of file character.
  if(ft==NULL) {                            iv) Data is read in forward direction only.
      printf("nCannot open the file");     v) Data is converted into the internal format
      fclose(fs);                                before being stored in memory.
      exit( 0);                             Binary File :
   }                                        i) Data is in the form of sequence of bytes.
   while((ch=getc(fs))!=EOF)                ii) There are no lines or newline character.
            putc(ch,ft);                    iii) An EOF marker is used.
   fclose(fs);                              iv) Data may be read in any direction.
   fclose(ft);                              v) Data stored in file are in same format that
}                                                they are stored in memory.
Random Access File
int main() {                                            ftell(file_pointer)
  int n,i;                                                -- returns the current position of file
  char *str="abcdefghijklmnopqrstuvwxyz";               pointer in terms of bytes from the
  FILE *fp = fopen("notes.txt","w");                    beginning.
  if(fp==NULL){                                         rewind(file-pointer)
      printf("nCannot open file."); exit(0);               -- moves the file pointer to the
  }                                                     starting of the file, and reset it.
  fprintf(fp,"%s",str);                                 fseek(fileptr, offset, position)
  fclose(fp);                                             – moves the file pointer to the
  fp = fopen("notes.txt","r");                          location (position + offset)
  printf("nText from position %d : nt“,ftell(fp));   position :
  fseek(fp, 3 ,SEEK_SET);                                 SEEK_SET – beginning of file
  for(i=0; i < 5; i++) putchar(getc(fp));                 SEEK_CUR – current position
  printf("nText from position %d : nt“,ftell(fp));     SEEK_END – end of the file
  fseek(fp, 4 ,SEEK_CUR);
  for(i=0; i < 6; i++) putchar(getc(fp));               output :
  fseek(fp, - 10 , SEEK_END);                           Text from position 3 :
  printf("nText from position %d : nt“,ftell(fp));       defgh
  for(i=0; i < 5; i++) putchar(getc(fp));               Text from position 12 :
  printf("nCurrent position : %d",ftell(fp));              mnopqr
  rewind(fp);                                           Text from position 16 :
  printf("nText from starting : nt");                    qrstu
  for(i=0;i < 8 ; i++) putchar(getc(fp));               Current position : 21
  fclose(fp);                                           Text from starting :
}                                                           abcdefgh
Formatted I / O                   /*Receives strings from keyboard
                                                 and writes them to file
/* using fscanf() and fprintf() functions */     and prints on screen*/
#include<stdio.h>                              #include<stdio.h>
int main( ) {                                  int main( ) {
   FILE *fp;                                     FILE *fp;
   int rno , i;                                  char s[80];
   float avg;                                    fp=fopen(“poem.txt","w");
   char name[20] , filename[15];                 if(fp==NULL) {
   printf("nEnter the filenamen");                 puts("Cannot open file");exit(0);
   scanf("%s",filename);                          }
   fp=fopen(filename,"w");                        printf("nEnter a few lines of text:n");
   for(i=1;i<=3;i++) {                            while(strlen(gets(s))>0){
      printf("Enter rno,name,average                 fputs(s,fp);
         of student no:%d",i);                       fputs("n",fp);
      scanf("%d %s %f",&rno,name,&avg);           }
      fprintf(fp,"%d %s %fn",rno,name,avg);      fclose(fp);
   }                                              fp=fopen(“poem.txt","r");
   fclose(fp);                                     if(fp==NULL){
   fp=fopen ( filename, "r“ );                        puts("Cannot open file"); exit(0);
   for(i=1;i<=3;i++) {                            }
      fscanf(fp,"%d %s %f",&rno,name,&avg);       printf("nContents of file:n");
      printf("n%d %s %f",rno,name,avg);          while(fgets(s,79,fp)!=NULL)
   }                                                  printf("%s",s);
   fclose(fp);                                    fclose(fp);
}                                              }
/* using putw() and getw() functions */                      Standard I / O
#include<stdio.h>
int main( ) {
                                              fputc()     fgetc()    Individual characters
   FILE *fp1,*fp2; int i,n;
   char *filename;                            fputs()     fgets()    Character Strings
   clrscr();                                  fprintf()   fscanf()   Formatted ASCII
   fp1=fopen("test.txt","w");
   for(i=10;i<=50;i+=10)                      fwrite()    fread()    Binary files
     putw(i,fp1);                             write()     read()     Low-level binary
   fclose(fp1);
   do {
     printf("nEnter the filename : n");
                                                          Predefined Streams
     scanf("%s",filename);
     fp2=fopen(filename,"r");
     if(fp2==NULL)
      printf("nCannot open the file");       NAME                    MEANING
   } while(fp2==NULL);                        stdin       Standard input (from keyboard)
   while(!feof(fp2)) {
                                              stdout      Standard output (to monitor)
     n=getw(fp2);
     if(n==-1) printf("nRan out of data");   stderr      Standard error output (to monitor)
     else printf("n%d",n);
   }                                          stdaux      Standard auxiliary (both input and
   fclose(fp2);                                           output)
   getch();                                   stdprn      Standard printer output(to printer)
}
Handling Records (structures) in a File
struct player {
  char name[40]; int age; int runs;
} p1,p2;
void main() {
    int i ; FILE *fp = fopen ( "player.txt", "w");
    if(fp == NULL) {
        printf ("nCannot open file."); exit(0);
    }
    for(i=0;i<3;i++) {
      printf("Enter name, age, runs of a player : ");
      scanf("%s %d %d",p1.name, &p1.age,&p1.runs);
      fwrite(&p1,sizeof(p1),1,fp);
    }
   fclose(fp);
   fp = fopen("player.txt","r");
   printf(“nRecords Entered : n");
   for(i=0;i<3;i++) {
      fread(&p2,sizeof(p2),1,fp);
      printf("nName : %snAge : %dnRuns : %d",p2.name,p2.age,p2.runs);
  }
  fclose(fp);
}
Error Handling:
While operating on files, there may be a chance of having certain errors which will cause
abnormal behavior in our programs.
1)Opening an file that was not present in the system.
2)Trying to read beyond the end of file mark.
3)Device overflow.
4)Trying to use a file that has not been opened.
5)Trying to perform an operation on a file when the file is opened for another type of
operation.
6)Attempting to write to a write-protected file.


  feof(fp) returns non-zero integer value if   /* program on ferror( ) and perror ( ) */
  we reach end of the file otherwise zero.      #include<stdio.h>
  ferror(fp) returns non-zero integer value    int main(){
  if an error has been detected otherwise         FILE *fp;
  zero                                            char ch;
                                                  fp=fopen("str.txt","w");
  perror(string)prints the string, a colon       ch=getc(fp);
  and an error message specified by the           if(ferror(fp))
  compiler                                            perror(“Error Raised : ");
  file pointer (fp) will return NULL if it        else
  cannot open the specified file.                     printf("%c",ch);
                                                  fclose(fp);
                                                }
#include<stdio.h>                                    fp will return NULL if unable to open
main(){                                              the file
FILE *fp1,*fp2;
int i,number;
char *filename;                                     feof(fp) returns 1 if it reaches end of
fp1=fopen("TEST.txt","w");                          file otherwise 0.
for(i=10;i<=50;i+=10)
             putw(i,fp1);
fclose(fp1);
file:
printf("nEnter the filenamen");
scanf("%s",filename);
fp2=fopen(filename,"r");
                                                Output:
if(fp2==NULL){                                  Enter the filename
    printf("nCannot open the file");           TETS.txt
                                                Cannot open the file
    printf("nType File name again");
     goto file;}                                Type the File name again
else{                                           Enter the filename
                                                TEST.txt
       for(i=1;i<=10;i++){
             number=getw(fp2);                  10
                                                20
                         if(feof(fp2)){
                 printf("nRan out of data");   30
                 break;}                        40
                                                50
else
    printf("n%d",number); } }                  Ran out of data.
fclose(fp2);}
Structure of FILE pointer                 File Management Functions

Type: FILE                                  rename(“old-filename",”new-filename");
   File control structure for streams.        -- It renames the file with the new name
typedef struct {
   short level;                             remove(“filename")
   unsigned      flags;                       -- It removes the file specified (macro)
   char    fd;
   unsigned char hold;                      unlink(“filename");
   short       bsize;                        -- It also removes the file name
   unsigned char *buffer, *curp;
   unsigned      istemp;                    fcloseall();
   short       token;                         -- Closes all the opened streams in the
 } FILE;                                         program except standard streams.

        File status functions               fflush(file_pointer)
                                               -- Bytes in the buffer transferred to file.
feof(file_pointer)
 -- to check if end of file has been        tmpfile ()
reached.                                      -- creates a temporary file, to be deleted
ferror(file_pointer)                             when program is completed.
 -- to check the error status of the file
clearerr(file_pointer)                      tmpnam(“filename”)
 -- to reset the error status of the file     -- creates a unique file name
• For More Materials, Text Books, Previous
  Papers & Mobile updates of B.TECH,
  B.PHARMACY, MBA, MCA of JNTU-HYD,JNTU-
  KAKINADA & JNTU-ANANTAPUR visit
  www.jntuworld.com

More Related Content

What's hot (20)

File handling in c
File handling in cFile handling in c
File handling in c
 
File management
File managementFile management
File management
 
File Management in C
File Management in CFile Management in C
File Management in C
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
7.0 files and c input
7.0 files and c input7.0 files and c input
7.0 files and c input
 
file handling1
file handling1file handling1
file handling1
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File in c
File in cFile in c
File in c
 
File in C language
File in C languageFile in C language
File in C language
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
C language updated
C language updatedC language updated
C language updated
 
Satz1
Satz1Satz1
Satz1
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
File handling in C
File handling in CFile handling in C
File handling in C
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
File operations in c
File operations in cFile operations in c
File operations in c
 
File Handling in C
File Handling in C File Handling in C
File Handling in C
 

Viewers also liked

What’s polite in New Zealand
What’s polite in New ZealandWhat’s polite in New Zealand
What’s polite in New ZealandLiz McLeay
 
M1 unit i-jntuworld
M1 unit i-jntuworldM1 unit i-jntuworld
M1 unit i-jntuworldmrecedu
 
T2 dc circuits
T2   dc circuitsT2   dc circuits
T2 dc circuitsSatyakam
 
VANY HUANG BIO 1.0
VANY HUANG BIO 1.0VANY HUANG BIO 1.0
VANY HUANG BIO 1.0vanyhuang
 
M1 unit vi-jntuworld
M1 unit vi-jntuworldM1 unit vi-jntuworld
M1 unit vi-jntuworldmrecedu
 
M1 unit ii-jntuworld
M1 unit ii-jntuworldM1 unit ii-jntuworld
M1 unit ii-jntuworldmrecedu
 
Applications of Differential Equations of First order and First Degree
Applications of Differential Equations of First order and First DegreeApplications of Differential Equations of First order and First Degree
Applications of Differential Equations of First order and First DegreeDheirya Joshi
 
Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2
Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2
Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2Shiwam Isrie
 
Circuit Analysis – DC Circuits
Circuit Analysis – DC CircuitsCircuit Analysis – DC Circuits
Circuit Analysis – DC CircuitsVesa Linja-aho
 
Electronics Projects List for Engineering Students
Electronics Projects List for Engineering StudentsElectronics Projects List for Engineering Students
Electronics Projects List for Engineering StudentsElectronics Hub
 

Viewers also liked (13)

VIT B.Tech BioMed Flow Chart
VIT B.Tech BioMed Flow ChartVIT B.Tech BioMed Flow Chart
VIT B.Tech BioMed Flow Chart
 
What’s polite in New Zealand
What’s polite in New ZealandWhat’s polite in New Zealand
What’s polite in New Zealand
 
M1 unit i-jntuworld
M1 unit i-jntuworldM1 unit i-jntuworld
M1 unit i-jntuworld
 
T2 dc circuits
T2   dc circuitsT2   dc circuits
T2 dc circuits
 
Mdt 280814
Mdt 280814Mdt 280814
Mdt 280814
 
VANY HUANG BIO 1.0
VANY HUANG BIO 1.0VANY HUANG BIO 1.0
VANY HUANG BIO 1.0
 
M1 unit vi-jntuworld
M1 unit vi-jntuworldM1 unit vi-jntuworld
M1 unit vi-jntuworld
 
M1 unit ii-jntuworld
M1 unit ii-jntuworldM1 unit ii-jntuworld
M1 unit ii-jntuworld
 
Biopsychology Chart I
Biopsychology Chart IBiopsychology Chart I
Biopsychology Chart I
 
Applications of Differential Equations of First order and First Degree
Applications of Differential Equations of First order and First DegreeApplications of Differential Equations of First order and First Degree
Applications of Differential Equations of First order and First Degree
 
Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2
Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2
Electronic devices-and-circuit-theory-10th-ed-boylestad-chapter-2
 
Circuit Analysis – DC Circuits
Circuit Analysis – DC CircuitsCircuit Analysis – DC Circuits
Circuit Analysis – DC Circuits
 
Electronics Projects List for Engineering Students
Electronics Projects List for Engineering StudentsElectronics Projects List for Engineering Students
Electronics Projects List for Engineering Students
 

Similar to Unit5 (2)

Programming in C
Programming in CProgramming in C
Programming in Csujathavvv
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
IN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdfIN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdfaratextails30
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.pptBhumaNagaPavan
 
File handling
File handlingFile handling
File handlingAns Ali
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 

Similar to Unit5 (2) (20)

Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
IN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdfIN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdf
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File handling in c
File handling in cFile handling in c
File handling in c
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
File handling
File handlingFile handling
File handling
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 

More from mrecedu

Brochure final
Brochure finalBrochure final
Brochure finalmrecedu
 
Filters unit iii
Filters unit iiiFilters unit iii
Filters unit iiimrecedu
 
Attenuator unit iv
Attenuator unit ivAttenuator unit iv
Attenuator unit ivmrecedu
 
Two port networks unit ii
Two port networks unit iiTwo port networks unit ii
Two port networks unit iimrecedu
 
Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)mrecedu
 
Unit6 jwfiles
Unit6 jwfilesUnit6 jwfiles
Unit6 jwfilesmrecedu
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfilesmrecedu
 
Unit2 jwfiles
Unit2 jwfilesUnit2 jwfiles
Unit2 jwfilesmrecedu
 
Unit1 jwfiles
Unit1 jwfilesUnit1 jwfiles
Unit1 jwfilesmrecedu
 
Unit7 jwfiles
Unit7 jwfilesUnit7 jwfiles
Unit7 jwfilesmrecedu
 
M1 unit v-jntuworld
M1 unit v-jntuworldM1 unit v-jntuworld
M1 unit v-jntuworldmrecedu
 
M1 unit iv-jntuworld
M1 unit iv-jntuworldM1 unit iv-jntuworld
M1 unit iv-jntuworldmrecedu
 
M1 unit iii-jntuworld
M1 unit iii-jntuworldM1 unit iii-jntuworld
M1 unit iii-jntuworldmrecedu
 
M1 unit viii-jntuworld
M1 unit viii-jntuworldM1 unit viii-jntuworld
M1 unit viii-jntuworldmrecedu
 
M1 unit vii-jntuworld
M1 unit vii-jntuworldM1 unit vii-jntuworld
M1 unit vii-jntuworldmrecedu
 
Unit vii
Unit viiUnit vii
Unit viimrecedu
 

More from mrecedu (20)

Brochure final
Brochure finalBrochure final
Brochure final
 
Unit i
Unit iUnit i
Unit i
 
Filters unit iii
Filters unit iiiFilters unit iii
Filters unit iii
 
Attenuator unit iv
Attenuator unit ivAttenuator unit iv
Attenuator unit iv
 
Two port networks unit ii
Two port networks unit iiTwo port networks unit ii
Two port networks unit ii
 
Unit 8
Unit 8Unit 8
Unit 8
 
Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
 
Unit4
Unit4Unit4
Unit4
 
Unit6 jwfiles
Unit6 jwfilesUnit6 jwfiles
Unit6 jwfiles
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfiles
 
Unit2 jwfiles
Unit2 jwfilesUnit2 jwfiles
Unit2 jwfiles
 
Unit1 jwfiles
Unit1 jwfilesUnit1 jwfiles
Unit1 jwfiles
 
Unit7 jwfiles
Unit7 jwfilesUnit7 jwfiles
Unit7 jwfiles
 
M1 unit v-jntuworld
M1 unit v-jntuworldM1 unit v-jntuworld
M1 unit v-jntuworld
 
M1 unit iv-jntuworld
M1 unit iv-jntuworldM1 unit iv-jntuworld
M1 unit iv-jntuworld
 
M1 unit iii-jntuworld
M1 unit iii-jntuworldM1 unit iii-jntuworld
M1 unit iii-jntuworld
 
M1 unit viii-jntuworld
M1 unit viii-jntuworldM1 unit viii-jntuworld
M1 unit viii-jntuworld
 
M1 unit vii-jntuworld
M1 unit vii-jntuworldM1 unit vii-jntuworld
M1 unit vii-jntuworld
 
Unit vii
Unit viiUnit vii
Unit vii
 
Unit vi
Unit viUnit vi
Unit vi
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Unit5 (2)

  • 1. typedef – to define new datatype bitfieds ‘ typedef ’ is a keyword,which allows you to struct playcard { specify a new name for a datatype which is unsigned pips ; already defined in c language program. unsigned suit ; Syntax: }; typedef <datatype> <newname> Above structure occupies 4 bytes of /* Re-defining int type as Integer type */ memory. But the member pips accepts a typedef int Integer; value between 1 to 13 and the member suit int main( ) { accepts any value of 0, 1, 2 and 3 . Interger a ,b , sub; So we can create a more packed a = 20,b = 10; representation of above structure with bitfields. sub = a - b; struct playcard { printf(“%d - %d = %d”, a, b, sub); unsigned pips : 4; } unsigned suit : 2; /* Defining structure with typedef to avoid }; repeated usage of struct keyword */ A bitfield is a set of adjacent bits within a single machine word. typedef struct { 4-bit field called pips that is capable of int hours; storing the 16 values 0 to 15, and a 2-bit int minutes; field called suit that is capable of storing } TIME ; values 0, 1, 2, and 3. So the entire structure int main( ) { variable occupies only one byte. TIME t1, t2 , *t; Note : arrays of bit fields and a pointer to t = (TIME *) calloc (10, sizeof( TIME )); address a bit field is not permitted. }
  • 2. Enumeration – a set of named integers, makes program more readable Declaration of enumeration : enum <enum_name> { member1, member2, …. …. …. } ; Example : enum option { YES, NO, CANCEL } ; By default YES has value 0, NO has value 1 and CANCEL has 2. enum direction { EAST = 1, SOUTH, WEST = 6, NORTH } ; Now EAST has value 1, SOUTH has value 2, WEST has value 6, and NORTH has value 7. Enumerated types can be converted implicitly or cast explicitly. int x = WEST ; /* Valid. x contains 6. */ enum direction y ; y = (enum direction ) 2 ; /* Valid. Y contains SOUTH */ #include<stdio.h> #include<stdio.h> int main() { enum color {RED = 1,ORANGE,GREEN }; int signal; int main() { printf ("ttt MENU nt1.RED n"); enum color signal; printf ("t2.ORANGEnt3.GREEN n“ ); printf ("ttt MENU nt1.RED n"); printf ("nt Enter the signal : “ ); printf ("t2.ORANGEnt3.GREENn"); scanf (“%d”, &signal ); printf ("nt Enter the signal : "); switch(signal) scanf ("%d", &signal); { switch(signal) { case 1: case RED: printf(“t Stop and Wait!"); break; printf("t Stop and Wait!"); break; case 2: case ORANGE: printf(“t Ready to start!"); break; printf("t Ready to start!"); break; case 3: case GREEN: printf(“t Start and go!"); break; printf("t Start and go!"); break; } } } }
  • 3. Console I / O Vs File I / O  scanf( ) and printf( ) functions read and write data which always uses the terminal (keyboard and screen) as the target.  It becomes confusing and time consuming to use large volumes of data through terminals.  The entire data is lost when either program terminates or computer is turned off.  Some times it may be necessary to store data in a manner that can be later retrieved and processed. This leads to employ the concept of FILES to store data permanently in the system. File Operations Record is logical group of data fields that comprise a single row of information, which 1. Creating a new file describes the characteristics of an object. 2. Opening an existing file File is a set of records that can be accessed 3. Reading from a file through the set of library functions. 4. Writing to a file A File is a place on disk where a group of 5. Moving to a specific related data ( records ) can be stored location in a file (seek) 6. Closing a file
  • 4. A Stream acts as an interface between a program and an input/output Device. Stream is a Sequence of data bytes, which is used to read and write data to a file. The streams that represent the input data of a program are known as Input Streams, where as the streams that represent the output data of a program are known as Output Streams. Input streams gets the data from different input devices such as keyboard and mouse and provide input data to the program. Output Streams obtain data from the program and write that on different Output Devices such as Memory or print them on the Screen. Types of Files 1.Text file : It can be thought of as a stream of characters that can be processed sequentially and in forward direction only. 2.Binary file : It is collection of bytes like images. 3.Sequential File: Data stored sequentially, to read the last record of the file, we need to traverse all the previous records before it. Ex: files on magnetic tapes. 4.Random Access File: Data can be accessed and modified randomly. We can read any record directly. Ex : files on disks.
  • 5. Steps involved using files /*program to write and read data from file*/ 1. Declaring FILE pointer variable : #include<stdio.h> Syntax : void main() { FILE *file_pointer1; FILE *fp; char ch; 2. Open a file using fopen() function : fp = fopen(“data.txt”, “w”); Syntax : if(fp == NULL) { fp= fopen(“filename”,“mode of access”); printf(“Cannot open file.”); exit(0); 3. fputc() – Used to write a character to } the file. printf(“Type text ( to stop press ‘.’ ) : ”); Syntax : while(ch != ‘.’) { fputc(character, file_pointer); ch = getche(); fputc(ch,fp); 4. fgetc() – Used to read a character to the } file. fclose(fp); Syntax : printf(“nContants read : “); fgetc(file_pointer); fp = fopen(“data.txt”,”r”); while(!feof(fp)) 5. Close a file using fclose() function : printf(“%d”, fgetc(fp)); Syntax : fclose(fp); fclose(file_pointer); }
  • 6. /* creating a new file */ file pointer used to handle files int main(){ char ch;FILE *fp; filepointer=fopen(“filename”,”mode”); printf("nEnter the textn"); printf("nt(Press ctrl+Z after completing text)n"); putc(character,filepointer); fp=fopen("str.txt","w"); while((ch=getchar())!=EOF) fclose(filepointer); putc(ch,fp); fclose(fp); } /* Reading the contents of existing file */ /* appending data to an existing file */ #include<stdio.h> int main() { int main() { FILE *fp; char ch; FILE *fp; printf("nEnter the textn"); char ch; printf("nt(Press ctrl+Z after fp=fopen("str.txt","r"); completing text)n"); while((ch=getc(fp))!=EOF) fp=fopen("str.txt","a"); printf("%c",ch); while((ch=getchar())!=EOF) fclose(fp); putc(ch,fp); } fclose(fp); }
  • 7. r -- open a file in read mode r+ -- open a file in read and write mode -- if file exits, the marker is positioned at -- if file exits, the marker is positioned beginning. at beginning. -- if file does not exist, error returned. -- if file does not exist, NULL returned. w -- open a file in write mode w+ -- open a file in read and write mode -- if file exits, all its data is erased. -- if file exits, all its data is erased. -- if file does not exist, it is created. -- if file does not exist, it is created. a -- open a file in append mode a+ -- open a file in read and append mode -- if file exits, the marker is positioned -- if file exits, the marker is positioned at end. at end. -- if file does not exist, it is created. -- if file does not exist, it is created. rb , wb , ab, rb+ , wb+ , ab+ are modes to operate a file as binary file. int main( ) { /* Without using w+ */ /* open a file in read and write mode */ FILE *fp; char ch; int main( ) { printf("nEnter the textn"); FILE *fp; char ch; fp=fopen("str1.txt","w"); printf("nEnter the textn"); while((ch=getchar())!='n‘)putc(ch,fp); fp=fopen("str1.txt","w+"); fclose(fp); while((ch=getchar())!='n') putc(ch,fp); fp=fopen("str1.txt","r"); rewind(fp); while((ch=getc(fp))!=EOF) while((ch=getc(fp))!=EOF) printf("%c",ch); printf("%c",ch); fclose(fp); fclose(fp); } }
  • 8. File Input / Output Functions fopen(fp, mode) Open existing file / Create new file fclose(fp) Closes a file associated with file pointer. closeall ( ) Closes all opened files with fopen() fgetc(ch, fp) Reads character from current position and advances the pointer to next character. fprintf( ) Writes all types of data values to the file. fscanf() Reads all types of data values from a file. gets() Reads string from a file. puts() Writes string to a file. getw() Reads integer from a file. putw() Writes integer to a file. fread() Reads structured data written by fwrite() function fwrite() Writes block of structured data to the file. fseek() Sets the pointer position anywhere in the file feof() Detects the end of file. rewind() Sets the record pointer at the beginning of the file. ferror() Reports error occurred while read/write operations fflush() Clears buffer of input stream and writes buffer of output stream. ftell() Returns the current pointer position.
  • 9. Text files Vs Binary Files /* Copying one binary file to other */ “rb”  open a file in read mode “wb”  open a file in write mode #include<stdio.h> int main( ) “ab”  open a file in append mode { “rb+”  open a pre-existing file in read and FILE *fs,*ft; write mode char ch; “wb+” open a file in read and write mode fs=fopen("pr1.exe","rb"); if(fs==NULL){ “ab+”  open a file in read and append mode printf("nCannot Open the file"); Text File : exit(0); i) Data are human readable characters. } ii) Each line ends with a newline character. ft=fopen("newpr1.exe","wb"); iii) Ctrl+z or Ctrl+d is end of file character. if(ft==NULL) { iv) Data is read in forward direction only. printf("nCannot open the file"); v) Data is converted into the internal format fclose(fs); before being stored in memory. exit( 0); Binary File : } i) Data is in the form of sequence of bytes. while((ch=getc(fs))!=EOF) ii) There are no lines or newline character. putc(ch,ft); iii) An EOF marker is used. fclose(fs); iv) Data may be read in any direction. fclose(ft); v) Data stored in file are in same format that } they are stored in memory.
  • 10. Random Access File int main() { ftell(file_pointer) int n,i; -- returns the current position of file char *str="abcdefghijklmnopqrstuvwxyz"; pointer in terms of bytes from the FILE *fp = fopen("notes.txt","w"); beginning. if(fp==NULL){ rewind(file-pointer) printf("nCannot open file."); exit(0); -- moves the file pointer to the } starting of the file, and reset it. fprintf(fp,"%s",str); fseek(fileptr, offset, position) fclose(fp); – moves the file pointer to the fp = fopen("notes.txt","r"); location (position + offset) printf("nText from position %d : nt“,ftell(fp)); position : fseek(fp, 3 ,SEEK_SET); SEEK_SET – beginning of file for(i=0; i < 5; i++) putchar(getc(fp)); SEEK_CUR – current position printf("nText from position %d : nt“,ftell(fp)); SEEK_END – end of the file fseek(fp, 4 ,SEEK_CUR); for(i=0; i < 6; i++) putchar(getc(fp)); output : fseek(fp, - 10 , SEEK_END); Text from position 3 : printf("nText from position %d : nt“,ftell(fp)); defgh for(i=0; i < 5; i++) putchar(getc(fp)); Text from position 12 : printf("nCurrent position : %d",ftell(fp)); mnopqr rewind(fp); Text from position 16 : printf("nText from starting : nt"); qrstu for(i=0;i < 8 ; i++) putchar(getc(fp)); Current position : 21 fclose(fp); Text from starting : } abcdefgh
  • 11. Formatted I / O /*Receives strings from keyboard and writes them to file /* using fscanf() and fprintf() functions */ and prints on screen*/ #include<stdio.h> #include<stdio.h> int main( ) { int main( ) { FILE *fp; FILE *fp; int rno , i; char s[80]; float avg; fp=fopen(“poem.txt","w"); char name[20] , filename[15]; if(fp==NULL) { printf("nEnter the filenamen"); puts("Cannot open file");exit(0); scanf("%s",filename); } fp=fopen(filename,"w"); printf("nEnter a few lines of text:n"); for(i=1;i<=3;i++) { while(strlen(gets(s))>0){ printf("Enter rno,name,average fputs(s,fp); of student no:%d",i); fputs("n",fp); scanf("%d %s %f",&rno,name,&avg); } fprintf(fp,"%d %s %fn",rno,name,avg); fclose(fp); } fp=fopen(“poem.txt","r"); fclose(fp); if(fp==NULL){ fp=fopen ( filename, "r“ ); puts("Cannot open file"); exit(0); for(i=1;i<=3;i++) { } fscanf(fp,"%d %s %f",&rno,name,&avg); printf("nContents of file:n"); printf("n%d %s %f",rno,name,avg); while(fgets(s,79,fp)!=NULL) } printf("%s",s); fclose(fp); fclose(fp); } }
  • 12. /* using putw() and getw() functions */ Standard I / O #include<stdio.h> int main( ) { fputc() fgetc() Individual characters FILE *fp1,*fp2; int i,n; char *filename; fputs() fgets() Character Strings clrscr(); fprintf() fscanf() Formatted ASCII fp1=fopen("test.txt","w"); for(i=10;i<=50;i+=10) fwrite() fread() Binary files putw(i,fp1); write() read() Low-level binary fclose(fp1); do { printf("nEnter the filename : n"); Predefined Streams scanf("%s",filename); fp2=fopen(filename,"r"); if(fp2==NULL) printf("nCannot open the file"); NAME MEANING } while(fp2==NULL); stdin Standard input (from keyboard) while(!feof(fp2)) { stdout Standard output (to monitor) n=getw(fp2); if(n==-1) printf("nRan out of data"); stderr Standard error output (to monitor) else printf("n%d",n); } stdaux Standard auxiliary (both input and fclose(fp2); output) getch(); stdprn Standard printer output(to printer) }
  • 13. Handling Records (structures) in a File struct player { char name[40]; int age; int runs; } p1,p2; void main() { int i ; FILE *fp = fopen ( "player.txt", "w"); if(fp == NULL) { printf ("nCannot open file."); exit(0); } for(i=0;i<3;i++) { printf("Enter name, age, runs of a player : "); scanf("%s %d %d",p1.name, &p1.age,&p1.runs); fwrite(&p1,sizeof(p1),1,fp); } fclose(fp); fp = fopen("player.txt","r"); printf(“nRecords Entered : n"); for(i=0;i<3;i++) { fread(&p2,sizeof(p2),1,fp); printf("nName : %snAge : %dnRuns : %d",p2.name,p2.age,p2.runs); } fclose(fp); }
  • 14. Error Handling: While operating on files, there may be a chance of having certain errors which will cause abnormal behavior in our programs. 1)Opening an file that was not present in the system. 2)Trying to read beyond the end of file mark. 3)Device overflow. 4)Trying to use a file that has not been opened. 5)Trying to perform an operation on a file when the file is opened for another type of operation. 6)Attempting to write to a write-protected file. feof(fp) returns non-zero integer value if /* program on ferror( ) and perror ( ) */ we reach end of the file otherwise zero. #include<stdio.h> ferror(fp) returns non-zero integer value int main(){ if an error has been detected otherwise FILE *fp; zero char ch; fp=fopen("str.txt","w"); perror(string)prints the string, a colon ch=getc(fp); and an error message specified by the if(ferror(fp)) compiler perror(“Error Raised : "); file pointer (fp) will return NULL if it else cannot open the specified file. printf("%c",ch); fclose(fp); }
  • 15. #include<stdio.h> fp will return NULL if unable to open main(){ the file FILE *fp1,*fp2; int i,number; char *filename; feof(fp) returns 1 if it reaches end of fp1=fopen("TEST.txt","w"); file otherwise 0. for(i=10;i<=50;i+=10) putw(i,fp1); fclose(fp1); file: printf("nEnter the filenamen"); scanf("%s",filename); fp2=fopen(filename,"r"); Output: if(fp2==NULL){ Enter the filename printf("nCannot open the file"); TETS.txt Cannot open the file printf("nType File name again"); goto file;} Type the File name again else{ Enter the filename TEST.txt for(i=1;i<=10;i++){ number=getw(fp2); 10 20 if(feof(fp2)){ printf("nRan out of data"); 30 break;} 40 50 else printf("n%d",number); } } Ran out of data. fclose(fp2);}
  • 16. Structure of FILE pointer File Management Functions Type: FILE rename(“old-filename",”new-filename"); File control structure for streams. -- It renames the file with the new name typedef struct { short level; remove(“filename") unsigned flags; -- It removes the file specified (macro) char fd; unsigned char hold; unlink(“filename"); short bsize; -- It also removes the file name unsigned char *buffer, *curp; unsigned istemp; fcloseall(); short token; -- Closes all the opened streams in the } FILE; program except standard streams. File status functions fflush(file_pointer) -- Bytes in the buffer transferred to file. feof(file_pointer) -- to check if end of file has been tmpfile () reached. -- creates a temporary file, to be deleted ferror(file_pointer) when program is completed. -- to check the error status of the file clearerr(file_pointer) tmpnam(“filename”) -- to reset the error status of the file -- creates a unique file name
  • 17. • For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH, B.PHARMACY, MBA, MCA of JNTU-HYD,JNTU- KAKINADA & JNTU-ANANTAPUR visit www.jntuworld.com