ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.

Slides:



Advertisements
Similar presentations
Files in C Rohit Khokher.
Advertisements

BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Structures and Unions Chapter 6. Structure A structure is an aggregate data type  Composed of two or more related variables called member/field/element.
File I/O.
 Types of files  Command line arguments  File input and output functions  Binary files  Random access.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
File IO and command line input CSE 2451 Rong Shi.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
C Programming Lecture 12 : File Processing
Structured Programming Approach Module VIII - Additional C Data Types File Handling Prof: Muhammed Salman Shamsi.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Adv. UNIX:fp/101 Advanced UNIX v Objectives of these slides: –a more detailed look at file processing in C Special Topics in Comp. Eng.
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
11 C File Processing.
Chapter 4 File Processing
Lecture 11 File input/output
TMF1414 Introduction to Programming
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
What you need for the 1st phase of project
CSE1320 Files in C Dr. Sajib Datta
Chapter 11 – File Processing
Lecture 15 Files.
CSE1320 Strings Dr. Sajib Datta
Text and Binary File Processing
File Input and Output.
File Handling.
Fundamental of Programming (C)
Chapter 12: File I/O.
FILE handeling.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
EECE.2160 ECE Application Programming
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip PSU ECE

Syllabus Introduction to File I/O Opening and Closing Files Character File I/O String File I/O Formatted File I/O Direct I/O

2 Introduction to File I/O Definition → A computer file is data that is stored on some form of durable medium. Basic file operations:  read – data is retrieved from a file  write – data is stored to a file  append – data is added to the end of a file

3 Major types of files:  Text Readable by humans (e.g., ASCII characters) More portable across systems Has end-of-line issues (Unix:LF, MSWin:CR+LF)  Binary Usually is not readable by humans (binary coding) Less portable across systems Has endian issues The efficiency of text versus binary depends on the type and amount of data stored in the file.

4 Text file storage format: Binary file storage format: 123   a a Each character is 1 byte wide. Total storage = 13 bytes '1''2''3''\n''1''6''3''5''1''8''4''0''\n' ASCII Hex Suppose 123 (hex 7b) is stored as type char (1 byte) Suppose (hex 00f98260) is stored as type int (4 bytes) Total storage = 5 bytes 7b 00 f Hex - Assuming big-endian format

5 Follow these steps when using file I/O functions:  Open the file Establishes I/O channel and enables access Only need to open file once  Read, write, or append to the file Perform as many operations as needed  Close the file Saves pending data and closes down channel Closed files can be re-opened again Multiple files can be open at the same time. Each file will have its own unique ID.

6 File I/O the "C" Way File I/O prototypes are declared in. ( #include ) When a file is opened, a unique file pointer is assigned to it. File pointers are of type FILE *. Declaration: FILE *fp; where fp is a pointer variable name.

7 A file pointer variable contains the address of a structure that holds file information. A file pointer is passed as an argument to a file I/O function to let it know which file to access. Another name for a file pointer is file handle.

8 Opening a File FILE * fopen (const char * filename, const char * mode); This function opens a file for read/write/append access. filename is a string with the name of the file to open. mode is a string containing the desired opening mode. A file pointer is returned. ModeIf file existsIf file does not exist "r" Opens the file for readingError "w" Opens a new file for writingCreates a new file "a" Opens the file for appendingCreates a new file "r+" Opens the file for reading & writingError "w+" Opens a new file for reading & writingCreates a new file "a+" Opens the file for reading & appendingCreates a new file

9 A binary file is opened by appending a ”b” to the mode. Example: fp = fopen("file.dat","rb"); /* Open binary file */ If successful, the assigned file pointer is returned. If not successful, the NULL value is returned. Always test the return value for NULL. Example: fp = fopen("myfile.txt","r"); if (fp == NULL) /* An error occurred */ printf("File open not successful\n"); else /* File opened OK */

10 Closing a File int fclose (FILE * fp); When a file is no longer needed, this function closes it. fp is the file pointer of the file to close. If successful, a zero (0) value is returned. If not successful, the EOF value is returned. The fclose() function ensures that any data still in the output buffer is written to the file before actually closing.

11 Test the return value to verify the operation’s success. Example: status = fclose(fp); if (status == EOF) /* An error occurred */ printf("File close not successful.\n"); else /* File closed OK */

12 Character File I/O Functions int fgetc (FILE * fp);  This reads a single character from a file.  If successful, the next character from the file is read in and returned (converted to type int). If not successful, the EOF value is returned. int fputc (int ch, FILE * fp);  This writes the character ch to a file.  If successful, the character written is returned. If not successful, the EOF value is returned.

13 String File I/O Functions char * fgets (char * str, int num, FILE * fp);  This reads a string from a file.  Up to num characters are read and then stored in str.  If successful, str is returned. If not successful, the NULL value is returned. int fputs (const char * str, FILE * fp);  This writes the string str to a file.  If successful, a non-negative value is returned. If not successful, the EOF value is returned.

14 Formatted File I/O Functions int fscanf (FILE * fp, const char * format, …);  This works just like scanf().  If successful, the # of items read is returned. If not successful, the EOF value is returned. int fprintf (FILE * fp, const char * format, …);  This works just like printf().  If successful, the # of characters written is returned. If not successful, a negative value is returned.

15 Status & Error Functions int feof (FILE * fp);  This checks if the end of the file has been reached.  Returns a non-zero value only if the previous read attempt failed. Miscellaneous C has several predefined file pointer values:  stdin-Standard input (console)  stdout-Standard output (console)  stderr-Standard error (console)

16 Algorithm for Reading Files with fscanf() 1. Attempt to open the file 2. Check that the file successfully opened 3. For each value in the file, read it in using fscanf() 4. Attempt to close the file 5. Check that the file successfully closed

17 Example: /* Program for reading from a text file */ #include int main (void) { FILE *ifile;/* Input file pointer */ float x, y;/* Input variables */ if ((ifile = fopen("data.txt","r")) == NULL) printf("File open not successful.\n"); else { /* Read values and display them */ while (fscanf(ifile,"%f %f",&x,&y) != EOF) printf("%.1f %.1f\n", x, y); if (fclose(ifile) == EOF) printf("File close not successful.\n"); } return 0; } Sample data.txt: Output:

18 Conceptual file operations: end scanf()==EOF → F x → 1.0 y → 3.4 Iteration #1 scanf()==EOF → F x → 2.0 y → 3.7 Iteration # end scanf()==EOF → F x → 3.0 y → 4.2 Iteration # end scanf()==EOF → T Exit Loop Iteration # end

19 Algorithm for Writing Files with fprintf() 1. Attempt to open the file 2. Check that the file opened successfully 3. For each data value, write it out using fprintf() 4. Attempt to close the file 5. Check that the file closed successfully

20 Example: Sample data stored within out.txt: Test file x is 5 /* Program for writing to a text file */ #include int main (void) { FILE *ofile;/* Output file pointer */ float x = 5; const char *s = "x is"; if ((ofile = fopen("out.txt","w")) == NULL) printf("File open not successful.\n"); else { /* Write out values */ fprintf(ofile, "Test file\n"); fprintf(ofile, "%s %d\n", s, x); if (fclose(ofile) == EOF) printf("File close not successful.\n"); } return 0; }

21 Example: /* Output operation: choose file or console */ #include int main (void) { FILE *fp; /* File pointer */ int mode, k; printf("File or console (f/c)? "); mode = getchar(); getchar(); printf("Enter integer: "); scanf("%d", &k); if (mode == 'f') { /* Output to file */ if ((fp = fopen("d.txt","w")) == NULL) { printf("Open error.\n"); exit(0); } else /* Output to console */ fp = stdout; printf("Writing data...\n"); fprintf(fp, "%d", k); fclose(fp); return 0; } /* Input operation: choose file or console */ #include int main (void) { FILE *fp; /* File pointer */ int mode, k; printf("File or console (f/c)? "); mode = getchar(); getchar(); if (mode == 'f') { /* Input from file */ if ((fp = fopen("d.txt","r")) == NULL) { printf("Open error.\n"); exit(0); } else /* Input from console */ fp = stdin; printf("Reading data...\n"); fscanf(fp, "%d", &k); printf("data = %d\n", k); fclose(fp); return 0; }

22 Direct I/O Functions size_t fread (void * ptr, size_t size, size_t nobj, FILE * fp);  Reads nobj number of objects, each of size size from file fp and stores them at address ptr.  The # of objects read is returned. size_t fwrite (const void * ptr, size_t size, size_t nobj, FILE * fp);  Writes nobj number of objects, each of size size, that are stored at address ptr to file fp.  The # of objects written is returned. The sizeof() operator returns the size of an object. Example: sizeof(int) returns 4 (int type is 4 bytes).

23 int fseek (FILE * fp, long int offset, int origin);  This sets the file position for fp. Subsequent reads or writes begin at the new position.  On error, non-zero is returned. origin macroSet origin of offset toSign of offset SEEK_SET Start of file+ SEEK_CUR Current position+ or - SEEK_END End of file- For binary files: file position = origin + offset For text files: offset must be zero, or a value return by ftell (and then origin must be SEEK_SET ). File startend file position

24 long ftell (FILE * fp);  This returns the current file position within fp.  If successful, current file position is returned On error, -1 is returned. void rewind (FILE * fp);  This resets the file position to the start of the file.

25 Example: /* Perform file I/O - Text file version */ #include int main (void) { FILE *fp;/* File pointer */ int k, x;/* Holds indep values */ double sr, y;/* Holds calc values */ /* Write data to text file */ if ((fp = fopen("tfile.txt","w")) == NULL) { printf("Error opening output file.\n"); exit(0); } printf("Writing text data...\n"); for (k = 0; k < 5; k++) { sr = sqrt(k); printf("%d %f\n", k, sr); fprintf(fp, "%d %f\n", k, sr); } fclose(fp); /* Read data from text file */ if ((fp = fopen("tfile.txt","r")) == NULL) { printf("Error opening input file.\n"); exit(0); }; printf("\nReading text data...\n"); for (k = 0; k < 5; k++) { fscanf(fp, "%d %lf", &x, &y); printf("%d %f\n", x, y); } fclose(fp); return 0; } Writing text data Reading text data

26 Example: /* Perform file I/O - Binary file version */ #include int main (void) { FILE *fp;/* File pointer */ int k, x;/* Holds indep values */ double sr, y;/* Holds calc values */ /* Write data to binary file */ if ((fp = fopen("bfile.bin","wb")) == NULL) { printf("Error opening output file.\n"); exit(0); } printf("Writing binary data...\n"); for (k = 0; k < 5; k++) { sr = sqrt(k); printf("%d %f\n", k, sr); fwrite(&k, sizeof(k), 1, fp); fwrite(&sr, sizeof(sr), 1, fp); } fclose(fp); /* Read data from binary file */ if ((fp = fopen("bfile.bin","rb")) == NULL) { printf("Error opening input file.\n"); exit(0); }; printf("\nReading binary data...\n"); for (k = 0; k < 5; k++) { fread(&x, sizeof(x), 1, fp); fread(&y, sizeof(y), 1, fp); printf("%d %f\n", x, y); } fclose(fp); return 0; } Writing binary data Reading binary data

27 Example: /* Perform file I/O - Binary file version */ #include int main (void) { FILE *fp;/* File pointer */ int k, x;/* Holds indep values */ double y;/* Holds calc values */ /* Read data from binary file */ if ((fp = fopen("bfile.bin","rb")) == NULL) { printf("Error opening input file.\n"); exit(0); } printf("Enter index to read (0 to 4): "); scanf("%d", &k); rewind(fp); fseek(fp, k*(sizeof(x)+sizeof(y)), SEEK_SET); fread(&x, sizeof(x), 1, fp); fread(&y, sizeof(y), 1, fp); printf("%d %f\n", x, y); fclose(fp); return 0; } Enter index to read (0 to 4):

28 Example: Saved as Text file (hex view) e a e □ a e □ a e a e □ □ a.00000□ Saved as Text file (ASCII view) ((10 characters+'\n')*(1 byte/character)) per line*(5 lines) = 55 bytes Saved as Binary file (hex view) f0 3f cd 3b 7f 66 9e a0 f6 3f aa 4c 58 e8 7a b6 fb 3f (int:4 bytes + double:8 bytes) per line*(5 lines) = 60 bytes