SlideShare a Scribd company logo
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

PPT
C Language Unit-5
DOC
Unit v
PPT
Unit5
DOCX
Understanding c file handling functions with examples
PPT
File handling in c
PDF
Chapter 13.1.10
PDF
Module 03 File Handling in C
PPT
File handling-c programming language
C Language Unit-5
Unit v
Unit5
Understanding c file handling functions with examples
File handling in c
Chapter 13.1.10
Module 03 File Handling in C
File handling-c programming language

What's hot (20)

PPTX
File handling in c
PPTX
File management
PPTX
File Management in C
PPSX
C programming file handling
PPT
7.0 files and c input
PPT
file handling1
PPT
File handling in 'C'
PPT
File in c
PPTX
File in C language
PPTX
C Programming Unit-5
PPT
File handling-dutt
PPTX
C language updated
DOCX
Satz1
PPT
DOCX
Unit 5 dwqb ans
PPTX
File handling in C
DOCX
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
PPTX
Data Structure Using C - FILES
PPTX
File Handling in C
File handling in c
File management
File Management in C
C programming file handling
7.0 files and c input
file handling1
File handling in 'C'
File in c
File in C language
C Programming Unit-5
File handling-dutt
C language updated
Satz1
Unit 5 dwqb ans
File handling in C
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
Data Structure Using C - FILES
File Handling in C
Ad

Viewers also liked (13)

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

Similar to Unit5 (2) (20)

PPT
Unit5 C
PPTX
Programming in C
PPTX
Programming in C
PPTX
want to learn files,then just use this ppt to learn
PPTX
c_pro_introduction.pptx
PPTX
File Organization
PDF
PPS Notes Unit 5.pdf
PPTX
files c programming handling in computer programming
PPSX
1file handling
PPT
Mesics lecture files in 'c'
PPTX
File handling in c
PPT
file.ppt
PPSX
File mangement
PPT
slides3_077.ppt
PPTX
File Handling in C Programming for Beginners
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PDF
637225560972186380.pdf
DOCX
PDF
Unit 5 File handling in C programming.pdf
PPTX
files concept in c program which is very use full
Unit5 C
Programming in C
Programming in C
want to learn files,then just use this ppt to learn
c_pro_introduction.pptx
File Organization
PPS Notes Unit 5.pdf
files c programming handling in computer programming
1file handling
Mesics lecture files in 'c'
File handling in c
file.ppt
File mangement
slides3_077.ppt
File Handling in C Programming for Beginners
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
637225560972186380.pdf
Unit 5 File handling in C programming.pdf
files concept in c program which is very use full

More from mrecedu (20)

PDF
Brochure final
PPT
Unit i
PPT
Filters unit iii
DOCX
Attenuator unit iv
PPT
Two port networks unit ii
PPT
Unit 8
PPT
Unit4 (2)
PPT
Unit4
PPT
Unit6 jwfiles
PPT
Unit3 jwfiles
PPT
Unit2 jwfiles
PPT
Unit1 jwfiles
PPT
Unit7 jwfiles
PPS
M1 unit v-jntuworld
PPS
M1 unit iv-jntuworld
PPS
M1 unit iii-jntuworld
PPS
M1 unit viii-jntuworld
PPS
M1 unit vii-jntuworld
PPS
Unit vii
PPS
Unit vi
Brochure final
Unit i
Filters unit iii
Attenuator unit iv
Two port networks unit ii
Unit 8
Unit4 (2)
Unit4
Unit6 jwfiles
Unit3 jwfiles
Unit2 jwfiles
Unit1 jwfiles
Unit7 jwfiles
M1 unit v-jntuworld
M1 unit iv-jntuworld
M1 unit iii-jntuworld
M1 unit viii-jntuworld
M1 unit vii-jntuworld
Unit vii
Unit vi

Recently uploaded (20)

PPTX
sap open course for s4hana steps from ECC to s4
PDF
Empathic Computing: Creating Shared Understanding
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation theory and applications.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPT
Teaching material agriculture food technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
sap open course for s4hana steps from ECC to s4
Empathic Computing: Creating Shared Understanding
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Understanding_Digital_Forensics_Presentation.pptx
Chapter 3 Spatial Domain Image Processing.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation_ Review paper, used for researhc scholars
Reach Out and Touch Someone: Haptics and Empathic Computing
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation theory and applications.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Teaching material agriculture food technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Building Integrated photovoltaic BIPV_UPV.pdf
Spectroscopy.pptx food analysis technology
NewMind AI Weekly Chronicles - August'25 Week I
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

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