SlideShare a Scribd company logo
1 of 37
Programming in C
Objectives


                In this session, you will learn to:
                   Read and write contents in a file
                   Use random access in files




     Ver. 1.0                                          Slide 1 of 37
Programming in C
Reading and Writing Contents in a File


                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.




     Ver. 1.0                                                            Slide 2 of 37
Programming in C
Opening Files


                •   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


     Ver. 1.0                                                               Slide 3 of 37
Programming in C
FILE Type Pointers


                •   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).




     Ver. 1.0                                                               Slide 4 of 37
Programming in C
The exit() Function


                • 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 ();
                      }




     Ver. 1.0                                                          Slide 5 of 37
Programming in C
Character Input-Output with Files


                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.




     Ver. 1.0                                                             Slide 6 of 37
Programming in C
Closing 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.




     Ver. 1.0                                                     Slide 7 of 37
Programming in C
Practice: 6.1


                1. What does the following code do?
                    while((c = fgetc (fp)) != EOF) {
                    if ((c >= ‘a’) && (c <= ‘z’))
                    c -= 32;
                    fputc(c, stdout); }
                2. 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:
                    a. 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

     Ver. 1.0                                                                 Slide 8 of 37
Programming in C
Practice: 6.1 (Contd.)


                Solution:




                            Microsoft Word
                               Document




     Ver. 1.0                                Slide 9 of 37
Programming in C
Practice: 6.2


                1. 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();
                       }

     Ver. 1.0                                                    Slide 10 of 37
Programming in C
Practice: 6.2 (Contd.)


                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);
                    } }

     Ver. 1.0                                                          Slide 11 of 37
Programming in C
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.




     Ver. 1.0                                                       Slide 12 of 37
Programming in C
Practice: 6.2 (Contd.)


                Solution:




                            Microsoft Word
                               Document




     Ver. 1.0                                Slide 13 of 37
Programming in C
Line Input and Output with Files


                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


     Ver. 1.0                                                                   Slide 14 of 37
Programming in C
Practice: 6.3


                1. State whether True or False:
                   Files created using the fputs() function will always have
                   records of equal length.
                3. 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


     Ver. 1.0                                                           Slide 15 of 37
Programming in C
Practice: 6.3 (Contd.)


                   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.
                3. Match the following functions with the values they can
                   return:
                    a. fgets() 1. NULL
                    b. fgetc() 2. EOF
                    c. fopen() 3. FILE type pointer




     Ver. 1.0                                                             Slide 16 of 37
Programming in C
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.




     Ver. 1.0                                                            Slide 17 of 37
Programming in C
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.




     Ver. 1.0                                                                Slide 18 of 37
Programming in C
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.




     Ver. 1.0                                                            Slide 19 of 37
Programming in C
Formatted Input and Output with Files


                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,..]);




     Ver. 1.0                                                         Slide 20 of 37
Programming in C
Practice: 6.4


                •   Rewrite the following printf() statement using the
                    function fprintf():
                       printf(“The test value is %d”, x);
                3. 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.




     Ver. 1.0                                                             Slide 21 of 37
Programming in C
Practice: 6.4 (Contd.)


                •   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.




     Ver. 1.0                                                           Slide 22 of 37
Programming in C
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.
     Ver. 1.0                                                               Slide 23 of 37
Programming in C
Practice: 6.4 (Contd.)


                Solution:




                            Microsoft Word
                               Document




     Ver. 1.0                                Slide 24 of 37
Programming in C
Using Random Access in Files


                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.




     Ver. 1.0                                                       Slide 25 of 37
Programming in C
The fseek () Function


                • 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.




     Ver. 1.0                                                                      Slide 26 of 37
Programming in C
The rewind () 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.




     Ver. 1.0                                                                 Slide 27 of 37
Programming in C
Practice: 6.5


                •   Write the equivalent of the function rewind() using
                    fseek().
                •   Assume the following representation of the first 30 bytes of
                    a file.




     Ver. 1.0                                                            Slide 28 of 37
Programming in C
Practice: 6.5 (Contd.)


                What will the current position on the file be after the
                following instructions are performed in sequence?
                 a.   fp = fopen ("FOR DEMO.DAT", “r”);
                 b.   fseek(fp, 29L, 1);
                 c.   rewind(fp);
                 d.   fgets(buffer, 20L, fp);
                 e.   fseek(fp, 4L, 1);




     Ver. 1.0                                                             Slide 29 of 37
Programming in C
Practice: 6.5 (Contd.)


                Solution:
                 1. fseek(fp, 0L, 0);
                 2. The following current positions are relative to the beginning of
                    the file:
                     a.   1
                     b.   30
                     c.   1
                     d.   20
                     e.   24




     Ver. 1.0                                                               Slide 30 of 37
Programming in C
Practice: 6.6


                1. 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)




     Ver. 1.0                                                                 Slide 31 of 37
Programming in C
Practice: 6.6 (Contd.)


                Solution:




                            Microsoft Word
                               Document




     Ver. 1.0                                Slide 32 of 37
Programming in C
Practice: 6.7


                •   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 }



     Ver. 1.0                                                         Slide 33 of 37
Programming in C
Practice: 6.7 (Contd.)


                Error listing:

                "inpcopy/.c", line 4: file undefined
                "inpcopy/.c". line 4: syntax error
                "inpcopy/.c", line 7: fp undefined
                "inpcopy/.c", line 7: w undefined
                "inpcopy/.c", line 7: learning: illegal
                  pointer/integer combination, op = "inpcopy/.c",
                  line 9: c undefined




     Ver. 1.0                                             Slide 34 of 37
Programming in C
Practice: 6.7 (Contd.)


                Solution:
                 1. Work out for your answer. The solution will be discussed in the
                    classroom session.




     Ver. 1.0                                                             Slide 35 of 37
Programming in C
Summary


               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.


    Ver. 1.0                                                             Slide 36 of 37
Programming in C
Summary (Contd.)


               – 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.




    Ver. 1.0                                                           Slide 37 of 37

More Related Content

What's hot

Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programmingMithun DSouza
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro headerhasan Mohammad
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it worksMark John Lado, MIT
 
Computer programming - turbo c environment
Computer programming - turbo c environmentComputer programming - turbo c environment
Computer programming - turbo c environmentJohn Paul Espino
 
Debug tutorial
Debug tutorialDebug tutorial
Debug tutorialDefri N
 
C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1Rumman Ansari
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for EngineeringVincenzo De Florio
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5Sowri Rajan
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
Declare Your Language: What is a Compiler?
Declare Your Language: What is a Compiler?Declare Your Language: What is a Compiler?
Declare Your Language: What is a Compiler?Eelco Visser
 
Introduction to C Unit 1
Introduction to C Unit 1Introduction to C Unit 1
Introduction to C Unit 1SURBHI SAROHA
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notesSrikanth
 
C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questionsadarshynl
 
Driver Debugging Basics
Driver Debugging BasicsDriver Debugging Basics
Driver Debugging BasicsBala Subra
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorialfreema48
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c languagetanmaymodi4
 

What's hot (20)

Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programming
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
 
Computer programming - turbo c environment
Computer programming - turbo c environmentComputer programming - turbo c environment
Computer programming - turbo c environment
 
Debug tutorial
Debug tutorialDebug tutorial
Debug tutorial
 
C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Declare Your Language: What is a Compiler?
Declare Your Language: What is a Compiler?Declare Your Language: What is a Compiler?
Declare Your Language: What is a Compiler?
 
A05
A05A05
A05
 
C tutorial
C tutorialC tutorial
C tutorial
 
Introduction to C Unit 1
Introduction to C Unit 1Introduction to C Unit 1
Introduction to C Unit 1
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questions
 
Driver Debugging Basics
Driver Debugging BasicsDriver Debugging Basics
Driver Debugging Basics
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Mpi
Mpi Mpi
Mpi
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
 

Viewers also liked

C programming session 02
C programming session 02C programming session 02
C programming session 02AjayBahoriya
 
C programming session 10
C programming session 10C programming session 10
C programming session 10AjayBahoriya
 
How does your media product represent particular social
How does your media product represent particular socialHow does your media product represent particular social
How does your media product represent particular socialhannahata2012
 
Research and planning March
Research and planning  March Research and planning  March
Research and planning March hannahata2012
 
C programming session 01
C programming session 01C programming session 01
C programming session 01AjayBahoriya
 
C programming session 16
C programming session 16C programming session 16
C programming session 16AjayBahoriya
 
C programming session 07
C programming session 07C programming session 07
C programming session 07AjayBahoriya
 

Viewers also liked (7)

C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C programming session 10
C programming session 10C programming session 10
C programming session 10
 
How does your media product represent particular social
How does your media product represent particular socialHow does your media product represent particular social
How does your media product represent particular social
 
Research and planning March
Research and planning  March Research and planning  March
Research and planning March
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
C programming session 16
C programming session 16C programming session 16
C programming session 16
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
 

Similar to C programming session 11

C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 
C programming session 14
C programming session 14C programming session 14
C programming session 14AjayBahoriya
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10patcha535
 
Build process in ST Visual Develop
Build process in ST Visual DevelopBuild process in ST Visual Develop
Build process in ST Visual DevelopGourav Kumar
 
C++ Help FilestreamWrite a program that reads the values from a f.pdf
C++ Help FilestreamWrite a program that reads the values from a f.pdfC++ Help FilestreamWrite a program that reads the values from a f.pdf
C++ Help FilestreamWrite a program that reads the values from a f.pdfMujeeb76
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C ProgrammingRavindraSalunke3
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptxSKUP1
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptxLECO9
 
C programming session 14
C programming session 14C programming session 14
C programming session 14Vivek Singh
 
Unit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptxUnit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptxraushankumarthakur7
 
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docxWrite a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docxSUKHI5
 
WK-12-13-file f classs 12 computer science from kv.
WK-12-13-file f classs 12 computer science from kv.WK-12-13-file f classs 12 computer science from kv.
WK-12-13-file f classs 12 computer science from kv.niwashannamalai0715
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 

Similar to C programming session 11 (20)

C programming session 08
C programming session 08C programming session 08
C programming session 08
 
C programming session 14
C programming session 14C programming session 14
C programming session 14
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Handout#01
Handout#01Handout#01
Handout#01
 
Build process in ST Visual Develop
Build process in ST Visual DevelopBuild process in ST Visual Develop
Build process in ST Visual Develop
 
Project report
Project reportProject report
Project report
 
C++ Help FilestreamWrite a program that reads the values from a f.pdf
C++ Help FilestreamWrite a program that reads the values from a f.pdfC++ Help FilestreamWrite a program that reads the values from a f.pdf
C++ Help FilestreamWrite a program that reads the values from a f.pdf
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
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
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
 
C programming session 14
C programming session 14C programming session 14
C programming session 14
 
Unit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptxUnit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptx
 
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docxWrite a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
 
WK-12-13-file f classs 12 computer science from kv.
WK-12-13-file f classs 12 computer science from kv.WK-12-13-file f classs 12 computer science from kv.
WK-12-13-file f classs 12 computer science from kv.
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 

Recently uploaded

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

C programming session 11

  • 1. Programming in C Objectives In this session, you will learn to: Read and write contents in a file Use random access in files Ver. 1.0 Slide 1 of 37
  • 2. Programming in C Reading and Writing Contents in a File 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. Ver. 1.0 Slide 2 of 37
  • 3. Programming in C Opening Files • 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 Ver. 1.0 Slide 3 of 37
  • 4. Programming in C FILE Type Pointers • 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). Ver. 1.0 Slide 4 of 37
  • 5. Programming in C The exit() Function • 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 (); } Ver. 1.0 Slide 5 of 37
  • 6. Programming in C Character Input-Output with Files 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. Ver. 1.0 Slide 6 of 37
  • 7. Programming in C Closing 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. Ver. 1.0 Slide 7 of 37
  • 8. Programming in C Practice: 6.1 1. What does the following code do? while((c = fgetc (fp)) != EOF) { if ((c >= ‘a’) && (c <= ‘z’)) c -= 32; fputc(c, stdout); } 2. 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: a. 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 Ver. 1.0 Slide 8 of 37
  • 9. Programming in C Practice: 6.1 (Contd.) Solution: Microsoft Word Document Ver. 1.0 Slide 9 of 37
  • 10. Programming in C Practice: 6.2 1. 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(); } Ver. 1.0 Slide 10 of 37
  • 11. Programming in C Practice: 6.2 (Contd.) 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); } } Ver. 1.0 Slide 11 of 37
  • 12. Programming in C 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. Ver. 1.0 Slide 12 of 37
  • 13. Programming in C Practice: 6.2 (Contd.) Solution: Microsoft Word Document Ver. 1.0 Slide 13 of 37
  • 14. Programming in C Line Input and Output with Files 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 Ver. 1.0 Slide 14 of 37
  • 15. Programming in C Practice: 6.3 1. State whether True or False: Files created using the fputs() function will always have records of equal length. 3. 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 Ver. 1.0 Slide 15 of 37
  • 16. Programming in C Practice: 6.3 (Contd.) 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. 3. Match the following functions with the values they can return: a. fgets() 1. NULL b. fgetc() 2. EOF c. fopen() 3. FILE type pointer Ver. 1.0 Slide 16 of 37
  • 17. Programming in C 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. Ver. 1.0 Slide 17 of 37
  • 18. Programming in C 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. Ver. 1.0 Slide 18 of 37
  • 19. Programming in C 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. Ver. 1.0 Slide 19 of 37
  • 20. Programming in C Formatted Input and Output with Files 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,..]); Ver. 1.0 Slide 20 of 37
  • 21. Programming in C Practice: 6.4 • Rewrite the following printf() statement using the function fprintf(): printf(“The test value is %d”, x); 3. 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. Ver. 1.0 Slide 21 of 37
  • 22. Programming in C Practice: 6.4 (Contd.) • 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. Ver. 1.0 Slide 22 of 37
  • 23. Programming in C 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. Ver. 1.0 Slide 23 of 37
  • 24. Programming in C Practice: 6.4 (Contd.) Solution: Microsoft Word Document Ver. 1.0 Slide 24 of 37
  • 25. Programming in C Using Random Access in Files 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. Ver. 1.0 Slide 25 of 37
  • 26. Programming in C The fseek () Function • 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. Ver. 1.0 Slide 26 of 37
  • 27. Programming in C The rewind () 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. Ver. 1.0 Slide 27 of 37
  • 28. Programming in C Practice: 6.5 • Write the equivalent of the function rewind() using fseek(). • Assume the following representation of the first 30 bytes of a file. Ver. 1.0 Slide 28 of 37
  • 29. Programming in C Practice: 6.5 (Contd.) What will the current position on the file be after the following instructions are performed in sequence? a. fp = fopen ("FOR DEMO.DAT", “r”); b. fseek(fp, 29L, 1); c. rewind(fp); d. fgets(buffer, 20L, fp); e. fseek(fp, 4L, 1); Ver. 1.0 Slide 29 of 37
  • 30. Programming in C Practice: 6.5 (Contd.) Solution: 1. fseek(fp, 0L, 0); 2. The following current positions are relative to the beginning of the file: a. 1 b. 30 c. 1 d. 20 e. 24 Ver. 1.0 Slide 30 of 37
  • 31. Programming in C Practice: 6.6 1. 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) Ver. 1.0 Slide 31 of 37
  • 32. Programming in C Practice: 6.6 (Contd.) Solution: Microsoft Word Document Ver. 1.0 Slide 32 of 37
  • 33. Programming in C Practice: 6.7 • 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 } Ver. 1.0 Slide 33 of 37
  • 34. Programming in C Practice: 6.7 (Contd.) Error listing: "inpcopy/.c", line 4: file undefined "inpcopy/.c". line 4: syntax error "inpcopy/.c", line 7: fp undefined "inpcopy/.c", line 7: w undefined "inpcopy/.c", line 7: learning: illegal pointer/integer combination, op = "inpcopy/.c", line 9: c undefined Ver. 1.0 Slide 34 of 37
  • 35. Programming in C Practice: 6.7 (Contd.) Solution: 1. Work out for your answer. The solution will be discussed in the classroom session. Ver. 1.0 Slide 35 of 37
  • 36. Programming in C Summary 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. Ver. 1.0 Slide 36 of 37
  • 37. Programming in C Summary (Contd.) – 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. Ver. 1.0 Slide 37 of 37

Editor's Notes

  1. Begin the session by explaining the objectives of the session.
  2. Discuss about streams with the students.
  3. Discusses various modes for opening a file. Compare the modes and discuss the situations where a specific mode should be chosen.
  4. 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.
  5. Discuss the student about the ways to determine the end of file when using the fgetc() function.
  6. Use this slide to test the student’s understanding on reading and writing contents in a file.
  7. Use this slide to test the student’s understanding on reading and writing contents in a file.
  8. Discuss the student about the ways to determine the end of file when using the fgets() function.
  9. Use this slide to test the student’s understanding on reading and writing contents in a file.
  10. Discuss the need for using the formatted input-output in a file.
  11. Use this slide to test the student’s understanding on formatted input-output in a file.
  12. Discuss sequential access and random access with their advantages and limitations.
  13. Use this slide to test the student’s understanding on random access in a file.
  14. Use this slide to test the student’s understanding on reading/writing contents in a file.
  15. Use this slide to test the student’s understanding on reading/writing contents in a file.
  16. Use this and the next 2 slides for summarizing the session.