SlideShare a Scribd company logo
In this session, you will learn to: Read and write contents in a file Use random access in files Objectives
File inputs-outputs is similar to input from/to the terminal. Files are treated as streams of characters. Function are available for single character as well as multiple character input-output from/to files. Reading and Writing Contents in a File
A file needs to be opened to read or to write contents in it. The  fopen()  function is used to open a file. The  fopen()  function returns a pointer of the  FILE  type data. The  fopen()  function opens a file in a specific access mode. The various modes in which a file can be opened are: r - Read-Only Mode w - Write-Only Mode a - Append Mode r+ - Read + Write Mode w+ - Write + Read Mode a+ - Read + Append Mode Opening Files
The  FILE  type pointer is: Returned when a file is opened by using the  fopen()  function. Used to manipulate a file. Used to check whether a file has opened successfully. The  stdin ,  stdout , and  stderr   FILE  pointers refer to the standard input device (keyboard) and standard output and error device (VDU). FILE Type Pointers
The  exit()  Function: Is used to terminate a program execution. Is used as shown in the following code snippet: if (argc ! = 3) { print (“invalid arguments \n”); exit (); } The exit() Function
The functions used for character input-output with files are: fgetc() : Reads one character at a time from a file, assigns it to a character variable, and moves the file pointer to the next character. It returns an integer type of value. fputc() : Writes one character at a time in a file. Character Input-Output with Files
The  fclose()  function is used to close files. Closing the file release the resources. The syntax of the  fclose()  function is: fclose (ptr1); Where  ptr1  is a  FILE  pointer. Closing Files
What does the following code do? while((c = fgetc (fp)) != EOF) { if ((c >= ‘a’) && (c <= ‘z’)) c -= 32; fputc(c, stdout); } Write a program called append, which appends the contents of the first file to the second file specified on the command line. The program should also terminate in the following situations: 2 arguments are not specified on the command line. In this case, the following message must be displayed: Usage: append file1 file2 b. In case the file to be read cannot be opened, the following message may be displayed:   Cannot open input file Practice: 6.1
Solution: Practice: 6.1 (Contd.)
Point out the errors in the following code: a. /* this program creates the file emp.dat */ main() { FILE point; fopen(“w”, “emp.dat”); : fclose(emp.dat); } b. /* this program reads the file emp.dat */ main() { #include<stdio.h> file*ptr; ptr = fopen(emp.dat); : ptr= fclose(); } Practice: 6.2
2. Given the following statements of a C program: fopen(“man.txt”, “r”); fclose(fileptr); What will the FILE declaration statement of this program be? 3. Point out the error(s) in the following code: #include<stdio.h> main() { char emp; FILE *pointer1; pointer1= fopen(“man1.txt”,”w”); while((inp = fgetc(pointer1)) != eof) { printf(“?%c”, inp); } } Practice: 6.2 (Contd.)
4. The  copy  command of DOS copies the contents of the first file named on the command line to the second file. Make appropriate changes to the  file-copy  program so that it works identical to the  copy  command. Practice: 6.2 (Contd.)
Solution: Practice: 6.2 (Contd.)
The functions used for line input and output with files are: fgets() :  Is used to read number of specified characters from a stream. Reads number of characters specified – 1 characters. Has the following syntax: fgets(str, 181, ptr1); Str  – Character array for storing the string 181  – Length of the string to be read ptr1-   FILE  pointer fputs() : Is used to output number of specified characters to a stream. Has the following syntax: fputs(str, ptr1); Str  – Character array to be written ptr1-   FILE  pointer Line Input and Output with Files
State whether True or False: Files created using the  fputs()  function will always have records of equal length. Consider the following C statement to input a record from a file called number-list: fgets (line, MAXLEN, file_ind); Given that  MAXLEN  is a  #define  and that all lines in the file number-list are 25 characters long what will the declaration statements for the parameters of  fgets()  be? 3. Assume that the file  number_list  contains the following records: 120 1305 Practice: 6.3
Given that the file has been opened and the first input statement executed is as follows: fgets(line, 3, file_ind); Which of the following will the array called line contain? a. 1 followed by \0. b. 12 followed by \0. c. 120 followed by \0. Match the following functions with the values they can return: a. fgets() 1.  NULL b. fgetc() 2.  EOF c. fopen() 3.  FILE  type pointer Practice: 6.3 (Contd.)
If a function can return more than one type of these values, state the conditions under which the values are returned. A utility called  hprint  has to be written in C, which will allow a user to display, on screen, any number of lines from the beginning of any file. The user has to specify both the number of lines and the file name on the command line in the following format: hprint number file-name The maximum line length is 80 characters. The program should handle possible errors. Practice: 6.3 (Contd.)
Solution: False.  fputs()  writes the contents of a string onto a file. So even if a string has size 100, but contains only 20 characters before a  \0 , only 20 characters get written. The declarations are:  #define MAXLEN 26/* macro definition outside main() */ char line[26]; b.  fgets()  will read either 3 - 1 characters , i.e. 2 characters, or until it comes across a newline character. Since the newline occurs after the third character, it will read in 2 characters from the first record. Practice: 6.3 (Contd.)
  4.  a.  1 b.  2  c.  1 and 3. ( NULL  in case file cannot be opened;  FILE  type pointer in case of successful open)  5.  The answer to this practice will be discussed in class. Work out your solution. Practice: 6.3 (Contd.)
The functions for formatted input and output with files are: fscanf() : Scans and formats input from a stream. Is similar to  scanf() . Has the following syntax: int fscanf(FILE *Stream, const char *format[,address,..]); fprintf(): Sends formatted output to a stream. Is similar to  printf() . Has the following syntax: int fprintf(FILE *Stream, const char *format[,address,..]); Formatted Input and Output with Files
Rewrite the following  printf()  statement using the function  fprintf() :   printf(“The test value is %d”, x); The following statement is written to input 2 fields from the keyboard:   scanf(“ %6s%d”, array, &num); It is rewritten as: fscanf(“%6s%d”, array, &num); This statement is erroneous. Give the correct  fscanf()  statement. Practice: 6.4
Write the appropriate statements to input fields from a record of a file called  alpha-doc , the first field being a  float  value, and the second field a string of size 10. In case the file does not have he required data, and the end-of-file occurs, the following message should be displayed:   End of file encountered. Practice: 6.4 (Contd.)
A utility called format is required to create a formatted report from a file called  manufact . This report is also to be stored on disk with suitable report headings. The name of the file to be created should be accepted during program execution. The program should also ask for a report title, which should appear after every 60 record of the file  manufact . The file  manufact  contains the following 3 fields separated by space.   Field  Size   Manufacturer Code    4   Name  20   Address 60 In the output file, the fields should be separated by one tab character. Practice: 6.4 (Contd.)
Solution: Practice: 6.4 (Contd.)
A file can be accessed using sequential access or random access. In sequential access, the file is always accessed from the beginning. In random access the file can be accessed arbitrarily from any position. Using Random Access in Files
The  fseek()  function: Is used for repositioning the current position on a file opened by the  fopen()  function. Has the following syntax: rtn = fseek (file-pointer, offset, from-where); Here: int rtn  is the value returned by  fseek()( 0 if successful and 1 if unsuccessful). file-pointer  is the pointer to the file. offset  is the number of bytes that the current position will shift on a file. from-where  is the position on the file from where the offset would be effective. The fseek () Function
The  rewind()  function: Is used to reposition the current position to the beginning of a file. Is useful for reinitializing the current position on a file. Has the following syntax: rewind(file-pointer); Here: file-pointer  is the pointer returned by the function  fopen() . After rewind() is executed, current position is always 1,  i.e. beginning of file. The rewind () Function
Write the equivalent of the function  rewind()  using  fseek() . Assume the following representation of the first 30 bytes of a file. Practice: 6.5
What will the current position on the file be after the following instructions are performed in sequence? a. fp = fopen (&quot;FOR DEMO.DAT&quot;, “r”); b. fseek(fp, 29L, 1); c.  rewind(fp); d. fgets(buffer, 20L, fp); e. fseek(fp, 4L, 1); Practice: 6.5 (Contd.)
Solution: 1. fseek(fp, 0L, 0); 2. The following current positions are relative to the beginning of the file: 1 30 1 20 24 Practice: 6.5 (Contd.)
Write a function to update the field balance in the file SAVINGS.DAT based on the following information. If balance is   Increment balance by < Rs 2000.00 Rs 150.50 Between Rs. 2000.00  Rs 200.00 and Rs 5000.00  <Rs 5000.00 Rs 300.40 The structure of the file  SAVINGS.DAT  is as follows. Account number Account holder's name Balance (5 bytes) (20 bytes) (5 bytes) Practice: 6.6
Solution: Practice: 6.6 (Contd.)
Go through the following program called  inpcopy.c  and its error listing on compilation and then correct the program: 1  #include <stdio.h> 2  main() 3  { 4  file fp; 5  char c; 6  7  fp = fopen(“file”, w); 8  9  while (( c = fgetc(stdin)) != EOF) 10  fputc(c,fp); 11 12  fclose(fp); 13 } Practice: 6.7
Error listing: &quot;inpcopy/.c&quot;, line 4: file undefined &quot;inpcopy/.c&quot;. line 4: syntax error &quot;inpcopy/.c&quot;, line 7: fp undefined &quot;inpcopy/.c&quot;, line 7: w undefined &quot;inpcopy/.c&quot;, line 7: learning: illegal pointer/integer combination, op = &quot;inpcopy/.c&quot;, line 9: c undefined Practice: 6.7 (Contd.)
Practice: 6.7 (Contd.) Solution: Work out for your answer. The solution will be discussed in the classroom session.
In this session, you learned that: C treats file input-output in much the same way as input-output from/to the terminal. A file needs to be opened to read or to write contents in it. The  fopen()  function is used to open a file. C allows a number of modes in which a file can be opened. When a file is opened by using the  fopen()  function, it returns a pointer that has to be stored in a FILE type pointer. This  FILE  type pointer is used to manipulate a file. The  exit()  function is used to terminate program execution. The  fgetc()  and  fputc()  functions are used for character input-output in files. After completing the I/O operations on the file, it should be closed to releases the resources. Summary
The  fclose()  function is used to close a file. The  fgets()  and  fputs()  functions are used for string input-output in files. The  fscanf()  and  fprintf()  functions are used for formatted input-output in files. In sequential access, the file is always accessed from the beginning. In random access the file can be accessed arbitrarily from any position. C provides the  fseek()  function for random access. The function  rewind()  is used to reposition the current position to the beginning of a file. Summary (Contd.)
Ad

More Related Content

What's hot (18)

File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
RavindraSalunke3
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
Prof. Dr. K. Adisesha
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Programming construction tools
Programming construction toolsProgramming construction tools
Programming construction tools
sunilchute1
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
Maria Stella Solon
 
Structures-2
Structures-2Structures-2
Structures-2
arshpreetkaur07
 
Unit iii
Unit iiiUnit iii
Unit iii
SHIKHA GAUTAM
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
Prerna Sharma
 
C programming session8
C programming  session8C programming  session8
C programming session8
Keroles karam khalil
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
FALLEE31188
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
RavindraSalunke3
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Programming construction tools
Programming construction toolsProgramming construction tools
Programming construction tools
sunilchute1
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
Prerna Sharma
 

Viewers also liked (11)

Session no 4
Session no 4Session no 4
Session no 4
Saif Ullah Dar
 
Session no 2
Session no 2Session no 2
Session no 2
Saif Ullah Dar
 
Session No1
Session No1 Session No1
Session No1
Saif Ullah Dar
 
Java script session 3
Java script session 3Java script session 3
Java script session 3
Saif Ullah Dar
 
C programming session 03
C programming session 03C programming session 03
C programming session 03
Dushmanta Nath
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
Saif Ullah Dar
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Session 3 Java Script
Session 3 Java ScriptSession 3 Java Script
Session 3 Java Script
Muhammad Hesham
 
Global Warming Project
Global Warming ProjectGlobal Warming Project
Global Warming Project
Dushmanta Nath
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
GLOBAL WARMING (GOOD PRESENTATION)
GLOBAL WARMING (GOOD PRESENTATION)GLOBAL WARMING (GOOD PRESENTATION)
GLOBAL WARMING (GOOD PRESENTATION)
elenadimo
 
C programming session 03
C programming session 03C programming session 03
C programming session 03
Dushmanta Nath
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
Saif Ullah Dar
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Global Warming Project
Global Warming ProjectGlobal Warming Project
Global Warming Project
Dushmanta Nath
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
GLOBAL WARMING (GOOD PRESENTATION)
GLOBAL WARMING (GOOD PRESENTATION)GLOBAL WARMING (GOOD PRESENTATION)
GLOBAL WARMING (GOOD PRESENTATION)
elenadimo
 
Ad

Similar to C programming session 08 (20)

C programming session 11
C programming session 11C programming session 11
C programming session 11
Vivek Singh
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
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
Muhammed Thanveer M
 
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 handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
file.ppt
file.pptfile.ppt
file.ppt
DeveshDewangan5
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
Sowri Rajan
 
Unit5
Unit5Unit5
Unit5
mrecedu
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
Handout#01
Handout#01Handout#01
Handout#01
Sunita Milind Dol
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
MalligaarjunanN
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
4 text file
4 text file4 text file
4 text file
hasan Mohammad
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)
leonard horobet-stoian
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
7.0 files and c input
7.0 files and c input7.0 files and c input
7.0 files and c input
Abdullah Basheer
 
Unit 8
Unit 8Unit 8
Unit 8
Keerthi Mutyala
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
Vivek Singh
 
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
Muhammed Thanveer M
 
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 handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
MalligaarjunanN
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)
leonard horobet-stoian
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
Ad

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 

C programming session 08

  • 1. In this session, you will learn to: Read and write contents in a file Use random access in files Objectives
  • 2. File inputs-outputs is similar to input from/to the terminal. Files are treated as streams of characters. Function are available for single character as well as multiple character input-output from/to files. Reading and Writing Contents in a File
  • 3. A file needs to be opened to read or to write contents in it. The fopen() function is used to open a file. The fopen() function returns a pointer of the FILE type data. The fopen() function opens a file in a specific access mode. The various modes in which a file can be opened are: r - Read-Only Mode w - Write-Only Mode a - Append Mode r+ - Read + Write Mode w+ - Write + Read Mode a+ - Read + Append Mode Opening Files
  • 4. The FILE type pointer is: Returned when a file is opened by using the fopen() function. Used to manipulate a file. Used to check whether a file has opened successfully. The stdin , stdout , and stderr FILE pointers refer to the standard input device (keyboard) and standard output and error device (VDU). FILE Type Pointers
  • 5. The exit() Function: Is used to terminate a program execution. Is used as shown in the following code snippet: if (argc ! = 3) { print (“invalid arguments \n”); exit (); } The exit() Function
  • 6. The functions used for character input-output with files are: fgetc() : Reads one character at a time from a file, assigns it to a character variable, and moves the file pointer to the next character. It returns an integer type of value. fputc() : Writes one character at a time in a file. Character Input-Output with Files
  • 7. The fclose() function is used to close files. Closing the file release the resources. The syntax of the fclose() function is: fclose (ptr1); Where ptr1 is a FILE pointer. Closing Files
  • 8. What does the following code do? while((c = fgetc (fp)) != EOF) { if ((c >= ‘a’) && (c <= ‘z’)) c -= 32; fputc(c, stdout); } Write a program called append, which appends the contents of the first file to the second file specified on the command line. The program should also terminate in the following situations: 2 arguments are not specified on the command line. In this case, the following message must be displayed: Usage: append file1 file2 b. In case the file to be read cannot be opened, the following message may be displayed: Cannot open input file Practice: 6.1
  • 10. Point out the errors in the following code: a. /* this program creates the file emp.dat */ main() { FILE point; fopen(“w”, “emp.dat”); : fclose(emp.dat); } b. /* this program reads the file emp.dat */ main() { #include<stdio.h> file*ptr; ptr = fopen(emp.dat); : ptr= fclose(); } Practice: 6.2
  • 11. 2. Given the following statements of a C program: fopen(“man.txt”, “r”); fclose(fileptr); What will the FILE declaration statement of this program be? 3. Point out the error(s) in the following code: #include<stdio.h> main() { char emp; FILE *pointer1; pointer1= fopen(“man1.txt”,”w”); while((inp = fgetc(pointer1)) != eof) { printf(“?%c”, inp); } } Practice: 6.2 (Contd.)
  • 12. 4. The copy command of DOS copies the contents of the first file named on the command line to the second file. Make appropriate changes to the file-copy program so that it works identical to the copy command. Practice: 6.2 (Contd.)
  • 14. The functions used for line input and output with files are: fgets() : Is used to read number of specified characters from a stream. Reads number of characters specified – 1 characters. Has the following syntax: fgets(str, 181, ptr1); Str – Character array for storing the string 181 – Length of the string to be read ptr1- FILE pointer fputs() : Is used to output number of specified characters to a stream. Has the following syntax: fputs(str, ptr1); Str – Character array to be written ptr1- FILE pointer Line Input and Output with Files
  • 15. State whether True or False: Files created using the fputs() function will always have records of equal length. Consider the following C statement to input a record from a file called number-list: fgets (line, MAXLEN, file_ind); Given that MAXLEN is a #define and that all lines in the file number-list are 25 characters long what will the declaration statements for the parameters of fgets() be? 3. Assume that the file number_list contains the following records: 120 1305 Practice: 6.3
  • 16. Given that the file has been opened and the first input statement executed is as follows: fgets(line, 3, file_ind); Which of the following will the array called line contain? a. 1 followed by \0. b. 12 followed by \0. c. 120 followed by \0. Match the following functions with the values they can return: a. fgets() 1. NULL b. fgetc() 2. EOF c. fopen() 3. FILE type pointer Practice: 6.3 (Contd.)
  • 17. If a function can return more than one type of these values, state the conditions under which the values are returned. A utility called hprint has to be written in C, which will allow a user to display, on screen, any number of lines from the beginning of any file. The user has to specify both the number of lines and the file name on the command line in the following format: hprint number file-name The maximum line length is 80 characters. The program should handle possible errors. Practice: 6.3 (Contd.)
  • 18. Solution: False. fputs() writes the contents of a string onto a file. So even if a string has size 100, but contains only 20 characters before a \0 , only 20 characters get written. The declarations are: #define MAXLEN 26/* macro definition outside main() */ char line[26]; b. fgets() will read either 3 - 1 characters , i.e. 2 characters, or until it comes across a newline character. Since the newline occurs after the third character, it will read in 2 characters from the first record. Practice: 6.3 (Contd.)
  • 19. 4. a. 1 b. 2 c. 1 and 3. ( NULL in case file cannot be opened; FILE type pointer in case of successful open) 5. The answer to this practice will be discussed in class. Work out your solution. Practice: 6.3 (Contd.)
  • 20. The functions for formatted input and output with files are: fscanf() : Scans and formats input from a stream. Is similar to scanf() . Has the following syntax: int fscanf(FILE *Stream, const char *format[,address,..]); fprintf(): Sends formatted output to a stream. Is similar to printf() . Has the following syntax: int fprintf(FILE *Stream, const char *format[,address,..]); Formatted Input and Output with Files
  • 21. Rewrite the following printf() statement using the function fprintf() : printf(“The test value is %d”, x); The following statement is written to input 2 fields from the keyboard: scanf(“ %6s%d”, array, &num); It is rewritten as: fscanf(“%6s%d”, array, &num); This statement is erroneous. Give the correct fscanf() statement. Practice: 6.4
  • 22. Write the appropriate statements to input fields from a record of a file called alpha-doc , the first field being a float value, and the second field a string of size 10. In case the file does not have he required data, and the end-of-file occurs, the following message should be displayed: End of file encountered. Practice: 6.4 (Contd.)
  • 23. A utility called format is required to create a formatted report from a file called manufact . This report is also to be stored on disk with suitable report headings. The name of the file to be created should be accepted during program execution. The program should also ask for a report title, which should appear after every 60 record of the file manufact . The file manufact contains the following 3 fields separated by space. Field Size Manufacturer Code 4 Name 20 Address 60 In the output file, the fields should be separated by one tab character. Practice: 6.4 (Contd.)
  • 25. A file can be accessed using sequential access or random access. In sequential access, the file is always accessed from the beginning. In random access the file can be accessed arbitrarily from any position. Using Random Access in Files
  • 26. The fseek() function: Is used for repositioning the current position on a file opened by the fopen() function. Has the following syntax: rtn = fseek (file-pointer, offset, from-where); Here: int rtn is the value returned by fseek()( 0 if successful and 1 if unsuccessful). file-pointer is the pointer to the file. offset is the number of bytes that the current position will shift on a file. from-where is the position on the file from where the offset would be effective. The fseek () Function
  • 27. The rewind() function: Is used to reposition the current position to the beginning of a file. Is useful for reinitializing the current position on a file. Has the following syntax: rewind(file-pointer); Here: file-pointer is the pointer returned by the function fopen() . After rewind() is executed, current position is always 1, i.e. beginning of file. The rewind () Function
  • 28. Write the equivalent of the function rewind() using fseek() . Assume the following representation of the first 30 bytes of a file. Practice: 6.5
  • 29. What will the current position on the file be after the following instructions are performed in sequence? a. fp = fopen (&quot;FOR DEMO.DAT&quot;, “r”); b. fseek(fp, 29L, 1); c. rewind(fp); d. fgets(buffer, 20L, fp); e. fseek(fp, 4L, 1); Practice: 6.5 (Contd.)
  • 30. Solution: 1. fseek(fp, 0L, 0); 2. The following current positions are relative to the beginning of the file: 1 30 1 20 24 Practice: 6.5 (Contd.)
  • 31. Write a function to update the field balance in the file SAVINGS.DAT based on the following information. If balance is Increment balance by < Rs 2000.00 Rs 150.50 Between Rs. 2000.00 Rs 200.00 and Rs 5000.00 <Rs 5000.00 Rs 300.40 The structure of the file SAVINGS.DAT is as follows. Account number Account holder's name Balance (5 bytes) (20 bytes) (5 bytes) Practice: 6.6
  • 33. Go through the following program called inpcopy.c and its error listing on compilation and then correct the program: 1 #include <stdio.h> 2 main() 3 { 4 file fp; 5 char c; 6 7 fp = fopen(“file”, w); 8 9 while (( c = fgetc(stdin)) != EOF) 10 fputc(c,fp); 11 12 fclose(fp); 13 } Practice: 6.7
  • 34. Error listing: &quot;inpcopy/.c&quot;, line 4: file undefined &quot;inpcopy/.c&quot;. line 4: syntax error &quot;inpcopy/.c&quot;, line 7: fp undefined &quot;inpcopy/.c&quot;, line 7: w undefined &quot;inpcopy/.c&quot;, line 7: learning: illegal pointer/integer combination, op = &quot;inpcopy/.c&quot;, line 9: c undefined Practice: 6.7 (Contd.)
  • 35. Practice: 6.7 (Contd.) Solution: Work out for your answer. The solution will be discussed in the classroom session.
  • 36. In this session, you learned that: C treats file input-output in much the same way as input-output from/to the terminal. A file needs to be opened to read or to write contents in it. The fopen() function is used to open a file. C allows a number of modes in which a file can be opened. When a file is opened by using the fopen() function, it returns a pointer that has to be stored in a FILE type pointer. This FILE type pointer is used to manipulate a file. The exit() function is used to terminate program execution. The fgetc() and fputc() functions are used for character input-output in files. After completing the I/O operations on the file, it should be closed to releases the resources. Summary
  • 37. The fclose() function is used to close a file. The fgets() and fputs() functions are used for string input-output in files. The fscanf() and fprintf() functions are used for formatted input-output in files. In sequential access, the file is always accessed from the beginning. In random access the file can be accessed arbitrarily from any position. C provides the fseek() function for random access. The function rewind() is used to reposition the current position to the beginning of a file. Summary (Contd.)

Editor's Notes

  • #2: Begin the session by explaining the objectives of the session.
  • #3: Discuss about streams with the students.
  • #4: Discusses various modes for opening a file. Compare the modes and discuss the situations where a specific mode should be chosen.
  • #5: Discuss the use of FILE type pointer to check whether a file has opened successfully. Also, discuss the situations where a FILE type pointer cannot open a file for read or write mode.
  • #7: Discuss the student about the ways to determine the end of file when using the fgetc() function.
  • #9: Use this slide to test the student’s understanding on reading and writing contents in a file.
  • #11: Use this slide to test the student’s understanding on reading and writing contents in a file.
  • #15: Discuss the student about the ways to determine the end of file when using the fgets() function.
  • #16: Use this slide to test the student’s understanding on reading and writing contents in a file.
  • #21: Discuss the need for using the formatted input-output in a file.
  • #22: Use this slide to test the student’s understanding on formatted input-output in a file.
  • #26: Discuss sequential access and random access with their advantages and limitations.
  • #29: Use this slide to test the student’s understanding on random access in a file.
  • #32: Use this slide to test the student’s understanding on reading/writing contents in a file.
  • #34: Use this slide to test the student’s understanding on reading/writing contents in a file.
  • #37: Use this and the next 2 slides for summarizing the session.