Lecture 9: Text & Binary Files Processing in C PDF

Summary

This document appears to be lecture notes for a course in C programming. It provides an introduction to text and binary files. The document discusses various aspects of file processing including file classifications, ways to classify files, examples, and considerations.

Full Transcript

Lecture 9: Text & Binary Files Processing in C Content I. Introduction II. Files and Streams III. Major Steps for Processing a File IV. File Error Handling V. Random Data Access Appendix...

Lecture 9: Text & Binary Files Processing in C Content I. Introduction II. Files and Streams III. Major Steps for Processing a File IV. File Error Handling V. Random Data Access Appendix Check the Notes section I. Introductio Storage of data in variables and arrays is temporary, such data is lost when a program terminates. n Files are used for permanent retention of data. Computers store files on secondary storage devices, such as hard drives, DVDs and flash drives. In this lecture, we explain how data files are created, updated and processed by C programs. We consider sequential-access and random-access file processing. …Continued There are many ways how to classify files  MATLAB provides a set of built‐in functions for accessing common file formats. −load, save for MATLAB formatted data in *.mat files −csvread, csvwrite – coma delimited numbers in *.csv files −xlsread, xlswrite – Microsoft Excel spreadsheet files *.xlsx Regardless of the file format, all files are subdivided into two Files major categories: Text Binary Files Files  C provides a set of generic functions for these two categories. Text File Processing A text file is a file of characters. The basis of its internal structure is a character. All characters (letters, digits and special characters) are stored in text files as ASCII codes. When content of a text Day ‐> 68 97 121 file is displayed, all 156 ‐> 49 53 54 ASCII codes are 38.098 ‐> 51 56 46 48 57 56 interpreted as corresponding characters Exampl e Anything wrong with this code? ---------------------------------------- char arr1 = { 1, 3, 5, 7, 12, 34, 11, 63, 7, 0}; int indx; for(indx = 0; indx < 10; indx++) printf("%c ", arr1[indx]); ---------------------------------------- The output is: " ? ---------------------------------------- Why?... The numbers are interpreted as ASCII codes, the 5 characters they present will be printed. … Continued ---------------------------------------- char arr1 = { 1, 3, 5, 7, 12, 34, 11, 63, 7, 0}; int indx; for(indx = 0; indx < 10; indx++) printf("%d ", (int)arr1[indx]); --------------------------------- ------- The output is: 1 3 5 7 12 34 11 63 7 0 --------------------------------- ------- 1. char 1 is converted to int 1. 2. printf function converts int 1 to its ASCII 49. 6 3. A computer monitor displays 1 as the graphical symbol of 49. II. Files and Streams A variable declared in a C program is a part of this program. A file is an external collection of data that is not part of the C program. variabl ??? es A Text File C program C must provide a linkage between the external file and the program. The linkage is provided by File Streams The Concept of File Stream A File Stream is an interface/linkage between a program and a physical device. It separates the program from the physical device by assigning each file a logical structure. variabl A File in Disk es strea m C program You work with a stream and the stream communicates with the actual device. Text & Binary File Streams A File Stream can be Text or Binary physical files do not have any special marker to indicate their type (a file name or its extension does not affect the file type) Unlike Text File Stream, A Binary File Stream does NOT perform any type conversion. Binary code of bina 35.68 A File variab 35.6 ry les 8 strea 51 53 46 m A File C 54 56 progra text m strea III. Major Steps for Processing a File: Step1: Declare stdio.h header file 1. Include the header file stdio.h #include  The library contains a set of functions to handle file I/O through streams.  Besides stdin defining the input –standard file stream, the (per stream stdiodefault libraryfrom also a defines identifiers: keyboard) stdout – standard output stream (per default to the stderr – standard error stream (per default to the monitor) monitor) Step2: Declare the File Stream variable 2. Declare file stream variables FILE *inFile; FILE *outFile; (stdin, and stderr are already stdout declared ) A= 56 stdout File inFile names.txt C progra File outFile m stdin marks.txt Step3: Link the file stream variable to the physical file 3. Associate the file streams with physical files: open files 3.1 TEXT file : open the file with the text flags to specify the access mode inFile = fopen( "names.txt" , “r"); outFile = fopen( "marks.txt", "w" ); A= 56 File stdout inFile names.txt C progra File outFile m stdin marks.txt Text File Opening Modes Function fopen() FILE* fopen(const char filename[], const char* mode); Mode Description Restriction Previous Content r Open file for reading must already preserved exist w Open file for writing created if erased doesn't exist a Open for writing. Output is created if preserved appended at the end doesn't exist Example:Open a file for output. If it does not exist, it’ll be created. If it already exists, the existing content will be erased: outFile = fopen("report.txt", "w"); …Continued 3.2 BINARY file stream: open the Files with the binary flags inBinFile = fopen( "names.dat", "rb" ); outBinFile = fopen( "marks.inf", "wb" ); A= 56 variab File les inData names.dat stdo ut C File progra outData stdi m marks.inf n Binary File Opening Modes Function fopen FILE* fopen(const char filename[], const char mode); Mode Description Restriction Previous Content rb Open file for reading must already preserved exist wb Open file for writing created if erased doesn't exist ab Open for writing. Output created if preserved is appended at the end doesn't exist  The same function is used for opening text and binary file streams.  Binary mode tells the I/O functions that format conversion of data and interpretation of all escape Open File: Error Handling Do NOT assume that a file stream is always successfully created − Incorrect file name inFile = fopen("names.txb", "r"); − Violation of restrictions may not FILE *inFile; exist, or inFile = fopen("names.txt", "r"); access may be restricted − Hardware failure You should always check the status of a stream after fopen : inFile = fopen("names.txt", "r"); Step 4: Read/Write operations 4. 4.1. Text file stream: use fprintf() and fscanf() functions for file I/O operations: fscanf(inFile, "%s", name); fprintf(outFile, "%f", mark); char name [] John File inFile names.txt C progra 83.6 File outFile m mark marks.txt …Continued 4.2. Binary file stream: use fwrite() and fread() functions for file I/O operations With Binary file streams, you have to perform operation per The fwrite()/fread() function writes/reads a given number BLOCK of items, all of the same size, from/to a memory buffer into/from a binary int fwrite( file stream. void *buffer, int sizeOfItem, int numOfItems, FILE *fp ); int fread ( void *buffer, int sizeOfItem, int numOfItems, FILE *fp ); Step 5: Close the file stream 5. Disconnect from the physical files: close the files: fclose(inFile); fclose(outFile); Files remain in Do not accidentally close stdin or the computer file stdout system when A= 56 they are File closed names.txt stdout inFile C File progra marks.txt outFile m stdin Example1: Formatted Output in a File In most application scenarios a text file created by a program will be printed and read by people. Information must be presented in a readable form. Output file streams can be formatted in the same manner as the standard output stream (easy to test and debug). Besides data, the file may contain supplementary information such as titles, comments, version number, etc. ---------------------------------------- Date: 24/09/2006 ---------------------------------------- Model: FinePix S3000 Example: Sales Number of Items Sold: 3 report Gross Amount: 1200.00 GST Paid: 120.00 Net Sale: 1080.00 …Continued St #include p1 int main(void) { int i; St FILE *salesReport; p2 stream char date[] = "24/09/2006"; a char fileName[] = "sale24_09_06.txt"; St char model[]==fopen( "FinePix S3000";"w" ); p3 salesReport fileName, a if( salesReport == NULL ) { fprintf(stderr, "Error opening %s", fileName); return -1; } OR printf(“Error opening %s”,fileName); … Continued for(i=0; i

Use Quizgecko on...
Browser
Browser