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

More Related Content

What's hot

Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
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
keeeerty
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
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!
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
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
keeeerty
 
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
Mahendra Yadav
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha 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 C
Ashim Lamichhane
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
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 handling
jhona2z
 
File mangement
File mangementFile mangement
File mangement
Jigarthacker
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 

What's hot (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
 

Similar to File handling(some slides only)

Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
Sowri Rajan
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10patcha535
 
File handling in c
File handling in cFile handling in c
File handling in c
mohit biswal
 
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
sangeeta borde
 
File management
File managementFile management
File management
AnishaThakkar2
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
4 text file
4 text file4 text file
4 text file
hasan Mohammad
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
RavindraSalunke3
 
file handling1
file handling1file handling1
file handling1student
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 
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 examplesMuhammed Thanveer M
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
MalligaarjunanN
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
Hemantha Kulathilake
 
File handling-c
File handling-cFile handling-c
C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 

Similar to 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
 

Recently uploaded

Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 

Recently uploaded (20)

Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 

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