SlideShare ist ein Scribd-Unternehmen logo
1 von 28
RANDOM ACCESS TO FILES
• So far we have seen file functions that are useful for
  read and write data sequentially.
• However, sometime we require to access only a
  particular part of a file.
• This can be achieved using fseek , ftell and rewind
  function available in I/O library.




                                                    1
ftell
• ftell takes a file pointer fp and return a number of type
  long, that corresponds to the current position.
        Example: n = ftell(fp);
• n would give the relative offset (in bytes) of the current
  position. This means that n bytes have already been read
  (or written).




                                                           2
fseek
• fseek function is used to move the file position to a desired location
   within the file. It takes the following form:
  fseek(file_ptr, offset, position);
• file_ptr is a pointer to the file concerned.
• offset is a number or variable of type long
• position is an integer number
• The offset specifies the number of positions (bytes) to be moved
   from the location specified by position.
• The position can take one of the following three values:
       Value Meaning
       0        Beginning of file
       1        Current position
       2        End of file
                                                                     3
• When the operation is successful, fseek returns a
  zero.
• If we attempt to move the file pointer beyond the
  file boundaries, an error occurs and fseek returns -1
  (minus one).




                                                    4
rewind
• Rewind takes a file pointer and resets the position to the
  start of the file.
rewind(fp);
n = ftell(fp);
• Above two line code would assign 0 to n because the file
   position has been set to the start of the file by rewind.




                                                           5
• Remember, the first byte in the file is numbered
  as 0, second as 1, and so on.
• Remember that whenever a file is opened for
  reading or writing, a rewind is done implicitly.




                                                 6
Statement                            Meaning

fseek(fp,0L,0)   Go to the beginning.(Similar to rewind).

fseek(fp,0L,1)   Stay at the current position(Rarely used).

fseek(fp,0L,2)   Go to the end of the file, past the last character of
                 the file.
fseek(fp,m,0)    Move to (m+1)th byte in the file

fseek(fp,m,1)    Go forward by m bytes

fseek(fp,-m,1)   Go backward by m bytes from the current position.

fseek(fp,-m,2)   Go backward by m bytes from the end.(Position
                 the file to the mth character from the end.)
                                                                    7
Write a program that uses the functions ftell and fseek.
#include <stdio.h>
void main()
  { FILE *fp;
    long n;
    char c;
    fp = fopen("RANDOM", "w");
while((c = getchar()) != EOF)
      putc(c,fp);

printf("No. of characters entered = %ldn", ftell(fp));
    fclose(fp);
fp = fopen("RANDOM","r");
                                                          8
    n = 0L;
while(feof(fp) == 0)
{
    fseek(fp, n, 0); /* Position to (n+1)th character */
    printf("Position of %c is %ldn", getc(fp),ftell(fp));
    n = n+5L;
   }
putchar('n');

fseek(fp,-1L,2); /* Position to the last character */
   do
      {
         putchar(getc(fp));
      }
while(!fseek(fp,-2L,1));
      fclose(fp);
  }
                                                             9
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z
No. of characters entered = 26
Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of    is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
                                 10
fgets
• Reads count - 1 characters from the given file stream and
  stores them in str.
• Characters are read until either a newline or an EOF is
  received or until the specified limit is reached.
• Declaration:
            char *fgets( char *str, int count, FILE *stream );
• Returns str on success or a NULL pointer on failure.




                                                           11
• Example of fgets:
#include <stdio.h>                                 sample.txt
#include <stdlib.h>         This is first line.
                              This is second line and longer than first line. The
    End.
    void main()
     {
       FILE *fp;
       char str[128];
       fp = fopen(“sample.txt", “r”);
      fgets(str, 126, fp);
     printf("%s", str); Output:
      fclose(fp);        This is first line.

}                           Note: Only first line displayed because new
                            line occurred.                                     12
fputs
• fputs writes text string to the stream. The string's null
  terminator is not written.
• Declaration: int fputs(const char *str, FILE *stream);
• Returns nonnegative on success and EOF on failure.
• Example of fputs:

  void main()
   {
     FILE *fp;

       fp = fopen(“test.txt", "w”);
       fputs(“This is written to test file.", fp);
       fclose(fp);
   }
                                                              13
fflush
• fflush empties the file io buffer and causes the
  contents to be written into the file immediately.
• The buffer is a block of memory used to temporarily
  store data before actually writing it onto the disk.
• The data is only actually written to the file when the
  buffer is full, the file stream is closed or when
  fflush() is called.
• The fflush function returns zero if successful or EOF
  if an error was encountered.


                                                    14
rename
• The function rename changes the name of the
   file oldfilename to newfilename.
• Declaration:
int rename(const char *old_filename, const char *new_filename )
• It returns 0​ upon success and non-zero value on error.
• Example of rename:
#include <stdio.h>
   void main()
{
       int renameFile = 0;
       renameFile = rename("MYFILE.txt", "HELLO.txt");
       if (renameFile != 0)
       printf("Error in renaming file.");
     getch();
   }                                                         15
remove
• Deletes the file whose name is specified in filename.
• Declaration: int remove ( const char * filename )
• 0 is returned if file is successfully deleted and a nonzero value
  is returned on failure.
#include <stdio.h>
#include <conio.h>

void main ()
{
if ( remove("myfile.txt”) != 0 )
printf( "Error deleting file" );
else
printf( "File successfully deleted" );
getch();
}
                                                              16
freopen
• freopen() is used to redirect the system-defined files stdin,
  stdout and stderr to some other file.
• Header file: stdio.h
• Declaration: freopen(“filename”, “mode”, stream);
• It Returns a pointer to stream on success or a null pointer
  on failure.




                                                          17
• Example of freopen:
  #include <stdio.h>
  #include <conio.h>
  void main()
   {
     FILE *fp;
      printf("This will display on the screen.n");
      if((fp = freopen(“test.txt", "w" ,stdout)) == NULL)
         {
          printf("Cannot open file.n");
        }
      printf("This will be written to the file OUT.");
      fclose(fp);
  }                                                         18
ferror
• ferror checks for a file error.
• Header File: stdio.h
• Declaration: int ferror(FILE *stream);
• It returns 0 if no error has occurred and nonzero integer if
  an error has occurred.
• ferror example:




                                                           19
• Example of ferror:
#include <stdio.h>
#include <conio.h>
void main()
{
     FILE *fp;
       fp=fopen(“test.txt", “w")
       putc('C', fp);

           if(ferror(fp))
       {
           printf("File Errorn");
            }

       fclose(fp);
   }                                 20
fgetpos and fsetpos
• fgetpos gets the file position indicator.
• fsetpos moves the file position indicator to a specific
  location in a file.

• Declaration: int fgetpos(FILE *stream, fpos_t *pos)
   – stream: A pointer to a file stream.
   – pos: A pointer to a file position.

• They returns zero on success and nonzero on failure



                                                            21
• Example of fgetpos and fsetpos:
#include <stdio.h>
void main ()
 {
 FILE     *fp;
 fpos_t position;
fp = fopen (“test.txt","w");
fgetpos (fp, &position);
fputs (“I like BCA", fp);
fsetpos (fp, &position);
fputs (“We“,fp);
fclose (fp);
}                                   22
Command line arguments
• What is a command line argument?
  It is a parameter supplied to a program when the program
  is invoked.
• main can take two arguments called argc and argv and the
  information contained in the command line is passed on to
  the program through these arguments, when main is called
  up by the system.
        main(int argc , char *argv[])
• The variable argc is an argument counter that counts the
  number of arguments on the command line.
• The argv is an argument vector and represents an array of
  character pointers that point to the command line
  arguments.                                             23
• Write a program that will receive a filename and a line of text as
  command line arguments and write the text to the file.
• Explaination of programme:
• Command line is:
cmdl test AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG
• Each word in the command line is an argument to the main and
  therefore the total number of arguments is 9.
• The argument vector argv[1] points to the string test and therefore
  the statement fp = fopen(argv[1], "w"); opens a file with the name
  test.
• The for loop that follows immediately writes the remaining 7
  arguments to the file test.




                                                                 24
#include <stdio.h>
void main(argc, argv)
  int argc;           /* argument count        */
  char *argv[];         /* list of arguments    */
  {
    FILE *fp;
    int i;
    char word[15];

   fp = fopen(argv[1], "w"); /* open file with name argv[1] */
   printf("nNo. of arguments in Command line = %dnn", argc);
   for(i = 2; i < argc; i++)
     fprintf(fp,"%s ", argv[i]);     /* write to file argv[1] */
   fclose(fp);
                                                                   25
/* Writing content of the file to screen */
   printf("Contents of %s filenn", argv[1]);
   fp = fopen(argv[1], "r");
   for(i = 2; i < argc; i++)
   {
     fscanf(fp,"%s", word);
     printf("%s ", word);
   }
   fclose(fp);
   printf("nn");

/* Writing the arguments from memory */
    for(i = 0; i < argc; i++)
    printf("%*s n", i*5,argv[i]);
  }                                              26
Output:
C:> cmdl test AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGG


 No. of arguments in Command line = 9

 Contents of test file

 AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG

C:>cmdl.EXE           //This is argv[0]
  TEXT                //This is argv[1]
    AAAAAA            //This is argv[2]
      BBBBBB
        CCCCCC
           DDDDDD
             EEEEEE
               FFFFFF
                  GGGGGG                                  27
28

Weitere ähnliche Inhalte

Was ist angesagt?

Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methodskeeeerty
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in pythonnitamhaske
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Edureka!
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing fileskeeeerty
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CMahendra Yadav
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
python file handling
python file handlingpython file handling
python file handlingjhona2z
 

Was ist angesagt? (20)

Python file handling
Python file handlingPython file handling
Python file handling
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Python-files
Python-filesPython-files
Python-files
 
File handling
File handlingFile handling
File handling
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File handling
File handlingFile handling
File handling
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
python file handling
python file handlingpython file handling
python file handling
 
File mangement
File mangementFile mangement
File mangement
 
Files in c++
Files in c++Files in c++
Files in c++
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 

Ähnlich wie File handling(some slides only)

Ähnlich wie File handling(some slides only) (20)

Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Unit5
Unit5Unit5
Unit5
 
Unit v
Unit vUnit v
Unit v
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
File handling in c
File handling in cFile handling in c
File handling in c
 
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 management
File managementFile management
File management
 
File management
File managementFile management
File management
 
4 text file
4 text file4 text file
4 text file
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
file handling1
file handling1file handling1
file handling1
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
 
Chap 12(files)
Chap 12(files)Chap 12(files)
Chap 12(files)
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
File handling-c
File handling-cFile handling-c
File handling-c
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 

Kürzlich hochgeladen

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Kürzlich hochgeladen (20)

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

File handling(some slides only)

  • 1. RANDOM ACCESS TO FILES • So far we have seen file functions that are useful for read and write data sequentially. • However, sometime we require to access only a particular part of a file. • This can be achieved using fseek , ftell and rewind function available in I/O library. 1
  • 2. ftell • ftell takes a file pointer fp and return a number of type long, that corresponds to the current position. Example: n = ftell(fp); • n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written). 2
  • 3. fseek • fseek function is used to move the file position to a desired location within the file. It takes the following form: fseek(file_ptr, offset, position); • file_ptr is a pointer to the file concerned. • offset is a number or variable of type long • position is an integer number • The offset specifies the number of positions (bytes) to be moved from the location specified by position. • The position can take one of the following three values: Value Meaning 0 Beginning of file 1 Current position 2 End of file 3
  • 4. • When the operation is successful, fseek returns a zero. • If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek returns -1 (minus one). 4
  • 5. rewind • Rewind takes a file pointer and resets the position to the start of the file. rewind(fp); n = ftell(fp); • Above two line code would assign 0 to n because the file position has been set to the start of the file by rewind. 5
  • 6. • Remember, the first byte in the file is numbered as 0, second as 1, and so on. • Remember that whenever a file is opened for reading or writing, a rewind is done implicitly. 6
  • 7. Statement Meaning fseek(fp,0L,0) Go to the beginning.(Similar to rewind). fseek(fp,0L,1) Stay at the current position(Rarely used). fseek(fp,0L,2) Go to the end of the file, past the last character of the file. fseek(fp,m,0) Move to (m+1)th byte in the file fseek(fp,m,1) Go forward by m bytes fseek(fp,-m,1) Go backward by m bytes from the current position. fseek(fp,-m,2) Go backward by m bytes from the end.(Position the file to the mth character from the end.) 7
  • 8. Write a program that uses the functions ftell and fseek. #include <stdio.h> void main() { FILE *fp; long n; char c; fp = fopen("RANDOM", "w"); while((c = getchar()) != EOF) putc(c,fp); printf("No. of characters entered = %ldn", ftell(fp)); fclose(fp); fp = fopen("RANDOM","r"); 8 n = 0L;
  • 9. while(feof(fp) == 0) { fseek(fp, n, 0); /* Position to (n+1)th character */ printf("Position of %c is %ldn", getc(fp),ftell(fp)); n = n+5L; } putchar('n'); fseek(fp,-1L,2); /* Position to the last character */ do { putchar(getc(fp)); } while(!fseek(fp,-2L,1)); fclose(fp); } 9
  • 10. Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z No. of characters entered = 26 Position of A is 0 Position of F is 5 Position of K is 10 Position of P is 15 Position of U is 20 Position of Z is 25 Position of is 30 ZYXWVUTSRQPONMLKJIHGFEDCBA 10
  • 11. fgets • Reads count - 1 characters from the given file stream and stores them in str. • Characters are read until either a newline or an EOF is received or until the specified limit is reached. • Declaration: char *fgets( char *str, int count, FILE *stream ); • Returns str on success or a NULL pointer on failure. 11
  • 12. • Example of fgets: #include <stdio.h> sample.txt #include <stdlib.h> This is first line. This is second line and longer than first line. The End. void main() { FILE *fp; char str[128]; fp = fopen(“sample.txt", “r”); fgets(str, 126, fp); printf("%s", str); Output: fclose(fp); This is first line. } Note: Only first line displayed because new line occurred. 12
  • 13. fputs • fputs writes text string to the stream. The string's null terminator is not written. • Declaration: int fputs(const char *str, FILE *stream); • Returns nonnegative on success and EOF on failure. • Example of fputs: void main() { FILE *fp; fp = fopen(“test.txt", "w”); fputs(“This is written to test file.", fp); fclose(fp); } 13
  • 14. fflush • fflush empties the file io buffer and causes the contents to be written into the file immediately. • The buffer is a block of memory used to temporarily store data before actually writing it onto the disk. • The data is only actually written to the file when the buffer is full, the file stream is closed or when fflush() is called. • The fflush function returns zero if successful or EOF if an error was encountered. 14
  • 15. rename • The function rename changes the name of the file oldfilename to newfilename. • Declaration: int rename(const char *old_filename, const char *new_filename ) • It returns 0​ upon success and non-zero value on error. • Example of rename: #include <stdio.h> void main() { int renameFile = 0; renameFile = rename("MYFILE.txt", "HELLO.txt"); if (renameFile != 0) printf("Error in renaming file."); getch(); } 15
  • 16. remove • Deletes the file whose name is specified in filename. • Declaration: int remove ( const char * filename ) • 0 is returned if file is successfully deleted and a nonzero value is returned on failure. #include <stdio.h> #include <conio.h> void main () { if ( remove("myfile.txt”) != 0 ) printf( "Error deleting file" ); else printf( "File successfully deleted" ); getch(); } 16
  • 17. freopen • freopen() is used to redirect the system-defined files stdin, stdout and stderr to some other file. • Header file: stdio.h • Declaration: freopen(“filename”, “mode”, stream); • It Returns a pointer to stream on success or a null pointer on failure. 17
  • 18. • Example of freopen: #include <stdio.h> #include <conio.h> void main() { FILE *fp; printf("This will display on the screen.n"); if((fp = freopen(“test.txt", "w" ,stdout)) == NULL) { printf("Cannot open file.n"); } printf("This will be written to the file OUT."); fclose(fp); } 18
  • 19. ferror • ferror checks for a file error. • Header File: stdio.h • Declaration: int ferror(FILE *stream); • It returns 0 if no error has occurred and nonzero integer if an error has occurred. • ferror example: 19
  • 20. • Example of ferror: #include <stdio.h> #include <conio.h> void main() { FILE *fp; fp=fopen(“test.txt", “w") putc('C', fp); if(ferror(fp)) { printf("File Errorn"); } fclose(fp); } 20
  • 21. fgetpos and fsetpos • fgetpos gets the file position indicator. • fsetpos moves the file position indicator to a specific location in a file. • Declaration: int fgetpos(FILE *stream, fpos_t *pos) – stream: A pointer to a file stream. – pos: A pointer to a file position. • They returns zero on success and nonzero on failure 21
  • 22. • Example of fgetpos and fsetpos: #include <stdio.h> void main () { FILE *fp; fpos_t position; fp = fopen (“test.txt","w"); fgetpos (fp, &position); fputs (“I like BCA", fp); fsetpos (fp, &position); fputs (“We“,fp); fclose (fp); } 22
  • 23. Command line arguments • What is a command line argument? It is a parameter supplied to a program when the program is invoked. • main can take two arguments called argc and argv and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system. main(int argc , char *argv[]) • The variable argc is an argument counter that counts the number of arguments on the command line. • The argv is an argument vector and represents an array of character pointers that point to the command line arguments. 23
  • 24. • Write a program that will receive a filename and a line of text as command line arguments and write the text to the file. • Explaination of programme: • Command line is: cmdl test AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG • Each word in the command line is an argument to the main and therefore the total number of arguments is 9. • The argument vector argv[1] points to the string test and therefore the statement fp = fopen(argv[1], "w"); opens a file with the name test. • The for loop that follows immediately writes the remaining 7 arguments to the file test. 24
  • 25. #include <stdio.h> void main(argc, argv) int argc; /* argument count */ char *argv[]; /* list of arguments */ { FILE *fp; int i; char word[15]; fp = fopen(argv[1], "w"); /* open file with name argv[1] */ printf("nNo. of arguments in Command line = %dnn", argc); for(i = 2; i < argc; i++) fprintf(fp,"%s ", argv[i]); /* write to file argv[1] */ fclose(fp); 25
  • 26. /* Writing content of the file to screen */ printf("Contents of %s filenn", argv[1]); fp = fopen(argv[1], "r"); for(i = 2; i < argc; i++) { fscanf(fp,"%s", word); printf("%s ", word); } fclose(fp); printf("nn"); /* Writing the arguments from memory */ for(i = 0; i < argc; i++) printf("%*s n", i*5,argv[i]); } 26
  • 27. Output: C:> cmdl test AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGG No. of arguments in Command line = 9 Contents of test file AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG C:>cmdl.EXE //This is argv[0] TEXT //This is argv[1] AAAAAA //This is argv[2] BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG 27
  • 28. 28