SlideShare ist ein Scribd-Unternehmen logo
1 von 16
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          3. Creating a new file
describes the characteristics of an object.          4. Opening an existing file
     File is a set of records that can be accessed   5. Reading from a file
through the set of library functions.                6. Writing to a file
      A File is a place on disk where a group of     7. Moving to a specific
related data ( records ) can be stored                  location in a file (seek)
                                                     8. 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
•Text file : It can be thought of as a stream of characters that can be processed sequentially and
in forward direction only.
•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);                               ii) Data are human readable characters.
  }                                         iii) Each line ends with a newline character.
  ft=fopen("newpr1.exe","wb");              iv) Ctrl+z or Ctrl+d is end of file character.
  if(ft==NULL) {                            v) Data is read in forward direction only.
      printf("nCannot open the file");     vi) Data is converted into the internal format
      fclose(fs);                                before being stored in memory.
      exit( 0);                             Binary File :
   }                                        viii)Data is in the form of sequence of bytes.
   while((ch=getc(fs))!=EOF)                ix) There are no lines or newline character.
            putc(ch,ft);                    x) An EOF marker is used.
   fclose(fs);                              xi) Data may be read in any direction.
   fclose(ft);                              xii) 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( ) {
   FILE *fp1,*fp2; int i,n;                   fputc()     fgetc()    Individual characters
   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.
3)Opening an file that was not present in the system.
4)Trying to read beyond the end of file mark.
5)Device overflow.
6)Trying to use a file that has not been opened.
7)Trying to perform an operation on a file when the file is opened for another type of
operation.
8)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
    printf("nType File name again");           Cannot open the file
     goto file;}                                Type the File name again
else{                                           Enter the filename
       for(i=1;i<=10;i++){                      TEST.txt
             number=getw(fp2);                  10
                         if(feof(fp2)){         20
                 printf("nRan out of data");   30
                 break;}                        40
else                                            50
    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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

File handling in c
File handling in cFile handling in c
File handling in c
 
File management
File managementFile management
File management
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
File Management in C
File Management in CFile Management in C
File Management in C
 
7.0 files and c input
7.0 files and c input7.0 files and c input
7.0 files and c input
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
file handling1
file handling1file handling1
file handling1
 
File in c
File in cFile in c
File in c
 
Satz1
Satz1Satz1
Satz1
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File in C language
File in C languageFile in C language
File in C language
 
File handling-c
File handling-cFile handling-c
File handling-c
 
C language updated
C language updatedC language updated
C language updated
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
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
 
File Handling in C
File Handling in C File Handling in C
File Handling in C
 
File operations in c
File operations in cFile operations in c
File operations 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
 

Ähnlich wie C Language Unit-5

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
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.pptBhumaNagaPavan
 
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
File handlingFile handling
File handlingAns Ali
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 

Ähnlich wie C Language Unit-5 (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
 
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
 
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
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
 
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
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
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
File handling
File handlingFile handling
File handling
 
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
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
CInputOutput.ppt
CInputOutput.pptCInputOutput.ppt
CInputOutput.ppt
 

Mehr von kasaragadda srinivasrao (8)

C Language Unit-8
C Language Unit-8C Language Unit-8
C Language Unit-8
 
C Language Unit-7
C Language Unit-7C Language Unit-7
C Language Unit-7
 
C Language Unit-6
C Language Unit-6C Language Unit-6
C Language Unit-6
 
C Language Unit-4
C Language Unit-4C Language Unit-4
C Language Unit-4
 
C Language Unit-3
C Language Unit-3C Language Unit-3
C Language Unit-3
 
C-Language Unit-2
C-Language Unit-2C-Language Unit-2
C-Language Unit-2
 
C Language Unit-1
C Language Unit-1C Language Unit-1
C Language Unit-1
 
Coupon tango site demo
Coupon tango site demoCoupon tango site demo
Coupon tango site demo
 

Kürzlich hochgeladen

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Kürzlich hochgeladen (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

C Language Unit-5

  • 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 3. Creating a new file describes the characteristics of an object. 4. Opening an existing file File is a set of records that can be accessed 5. Reading from a file through the set of library functions. 6. Writing to a file A File is a place on disk where a group of 7. Moving to a specific related data ( records ) can be stored location in a file (seek) 8. 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 •Text file : It can be thought of as a stream of characters that can be processed sequentially and in forward direction only. •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); ii) Data are human readable characters. } iii) Each line ends with a newline character. ft=fopen("newpr1.exe","wb"); iv) Ctrl+z or Ctrl+d is end of file character. if(ft==NULL) { v) Data is read in forward direction only. printf("nCannot open the file"); vi) Data is converted into the internal format fclose(fs); before being stored in memory. exit( 0); Binary File : } viii)Data is in the form of sequence of bytes. while((ch=getc(fs))!=EOF) ix) There are no lines or newline character. putc(ch,ft); x) An EOF marker is used. fclose(fs); xi) Data may be read in any direction. fclose(ft); xii) 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( ) { FILE *fp1,*fp2; int i,n; fputc() fgetc() Individual characters 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. 3)Opening an file that was not present in the system. 4)Trying to read beyond the end of file mark. 5)Device overflow. 6)Trying to use a file that has not been opened. 7)Trying to perform an operation on a file when the file is opened for another type of operation. 8)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 printf("nType File name again"); Cannot open the file goto file;} Type the File name again else{ Enter the filename for(i=1;i<=10;i++){ TEST.txt number=getw(fp2); 10 if(feof(fp2)){ 20 printf("nRan out of data"); 30 break;} 40 else 50 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