380 likes | 559 Views
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 in a directory The path is the directory to get to the file. Each file in a directory has a unique filename. File Actions.
E N D
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 in a directory • The path is the directory to get to the file. • Each file in a directory has a unique filename.
File Actions • Files can be • Written • Read • Appended (Added) • Files need to be identified before operating on them (path/filename) • Many files can be opened at the same time!
Using Files • Indicate the file to use and how you want to use it • path/filename or filename • read/write/append • Perform the write or read operation • Indicate you have finished using the file.
Book Analogy – Choose and open book • You can think of using files in the same way that you would use a book from your bookshelf at home. • In order to use a book (read from it or write to it), you must first open the book. This involves using the name of the book to find it amongst the other books on the bookshelf. Also the type of book you will get will depend upon whether you want to read it (printed text only eg text book) or write to it (blank pages eg note book). - This is the same as opening a file.
Book Analogy – Bookmark position • Once you have the book you will want to identify the book and where you are in the book using a bookmark. If you have more than one book then you will use more than one bookmark. - This is the same as the file pointer. • You can read from the book or write to the book you have chosen. This means that you must use the bookmark to identify both the book and the page in the book you are using. - This is the same since all file access requires a file pointer.
Book Analogy – Close Book • Once you have finished using the book, you will close the book and put it back on the book. You can then put the bookmark away. - This is the same as closing the file. Any data will be written to the file when it is closed.
Text Files • Text files are used to store ASCII data. • Text files consist of ASCII data and a special end of file marker to show the end of the file. • ctrl-Z in Windows (Ascii character 26) • ctrl-D in UNIX (Ascii character 4) ASCII Text<EOL> ASCII Text<EOL> ASCII Text<EOL> ASCII Text<EOL> Sample of an ASCII file!<EOL> ASCII Text <EOL> <EOF>
Text Files • File operations require special Input/Output routines which can be found in <stdio.h> • More than one file can be used at the same time in a program. • Each file needs to be identified by it’s own file pointer. • A file pointer is used by the OS to keep track of the operations upon the file.
File Pointers in C • Each file is referred to by a special variable called a file pointer. eg FILE *fp; • One file pointer is used per file. Therefore if more than one file is to be used, then more than one file pointer must be declared. eg FILE*fp_in,*fp_out; • The file pointer is assigned when the file is opened for use. This requires the use of the fopen() function. The open function requires the filename and how the file is to be accessed (read, write, read/write etc).
Text Files • The file data can be accessed using fgetch(), fprintf(), fscanf(), fgets(). These are same as the I/O functions you are familiar with, except they require a file pointer. The characters in the file are read sequentially. • The file pointer is deassigned when you close a file. If you have written any data to the file, the file will be updated when the file is closed.
Opening Files – fopen() • Files are opened using fopen() fopen(filename, mode) • filename is a string containing the name of the file to be opened. • mode is a string stating how the file is to be used • “r” read only text file • “w” write only text file • “rw” read and write text file • “a” appending text file. Writes to the end of the file. • “rb” read binary file. • “wb” write binary file. • “rwb” read & write binary file • fopen() returns the file pointer if the file could be opened. • fopen() returns a NULL if the file could not be opened. If the happens end the program with exit(-1).
Example of fopen() #include <stdio.h> #include <stdlib.h> int main(void) { FILE *in ; /* declare the input file pointer */ if ( (in = fopen("icp.txt","r")) == NULL) { // display message and reason for failure perror("Error: Cannot open file icp.txt") ; exit(-1) ; } }
Another example of fopen() #include <stdio.h> #include <stdlib.h> int main(void) { FILE *in ; /* declare the input file pointer */ char filename[80] ; char error_msg[80] ; printf("Please enter the file to open"); scanf("%s",filename) ; if ( (in = fopen(filename,"r")) == NULL) { // display message and reason for failure with filename sprintf(error_msg,"Error: Cannot open file %s",filename); perror(error_msg) ; exit(-1) ; } }
Closing Files • Files are closed using the fclose() function. fclose(file_pointer) where • file_pointer is the file_pointer returned from fopen().
Data Access • The data is accessed with functions similar to the ones you have used before to get data from the keyboard. • The file access functions are fprintf(), fscanf(), fgetc(), fputc(), fgets(), fputs(). • The file access functions have a f prefix and must have a file pointer as an argument. The file pointer is used to identify the file to be accessed. • All access is performed sequentially. The file access function automatically take into account the position in the file. • The file access function prototypes are found in <stdio.h>
End of File • The file is marked by an end of file character. • EOF is a #define in the <stdio.h> used to denote the End Of File character. • When the end of file is reached • character input functions return EOFcharacter • string input functions return a NULLpointer • scanf() function returns EOF • A feof() function can be used to determine whether the end of the file has been reached. This means that the EOF must have already been read by one of the input functions. This must be used with binary files.
End of File Syntax: feof(file_pointer) where • file_pointer is used as a marker to indicate the file you are working with. For each file there must be a new file pointer. • Returns true, if End Of File has been found otherwise returns false.
Reading Files • The basic sequence for reading a file is declare file pointer open the file WHILE (NOT the end of the file) • read data from file • process the data close the file
Writing Files • The basic sequence for writing a file is declare file pointer open the file • write the data to the file close the file
Using the File Pointer with Functions • The file pointer is declared as FILE *name ; in the program. • When declaring a file pointer in the function definition, the declaration for the file pointer is FILE *local_name • In the prototype use FILE * as the data type of the file pointer. • When calling a function with the file pointer, just use the name of the file_pointer
Example to write 99 to a file #include <stdio.h> #include <stdlib.h> void fn(FILE *) ; /* prototype */ int main(void) { FILE *fp ; /* open the file */ if ( (fp = fopen("file.txt","w")) == NULL) { perror("Error: Cannot open File file.txt") ; exit(-1) ; } fn(fp) ; /* call the function */ fclose(fp) ; /* close the file */ }
Example (cont) /* function with the file_pointer passed as an argument */ void fn(FILE *file_pointer) { int value ; value = 99 ; fprintf(file_pointer, "%d", value ) ; }
Program to print the contents of a text file #include <stdio.h> #include <stdlib.h> int main(void) { char line[81] ; /* line to read from file */ FILE *in ; /* declare the input file pointer */ /* open the file */ if ( (in = fopen("file.txt","r")) == NULL) { perror("Error: Cannot open File file.txt") ; exit(-1) ; } /* read and print the contents of the file */ while (fgets(line,81,in) != NULL) /* NULL means EOF */ printf("%s",line) ; /* close the file */ fclose(in) ; }
Example to read & display a stock list • This program will read a list of stock from a file and display the contents in the required format. • The user must be asked for the filename File FormatOutput Format description price\n description $price\n Eg Eg flour 1.25 flour $1.25 stamps 1.50 stamps $1.50 dvd 18.23 dvd $18.23
Example (cont) #include <stdio.h> #include <stdlib.h> int main(void) { char line[81] ; /* line to read from file */ char fname[40] ; /* file name */ char descript[10] ; /* description of item */ float price ; /* cost of item */ FILE *in ; /* declare the input file pointer */ /* get the filename from the user */ printf("Enter the filename ") ; scanf("%s",fname) ;
Example (cont) /* open the file */ if ( (in = fopen(fname,"r")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ; } /* print the contents of the file */ while (fscanf(in,"%s %g",descript,&price)!= EOF) /*check the EOF reached */ printf("%s $%.2g\n",descript,price) ; /* close the file */ fclose(in) ; }
Example to display file contents in Ucase #include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(void) { char fname[40] ; /* file name */ char ch ; /* character to read*/ FILE *in ; /* declare the input file pointer */ printf("Enter the filename ") ; /* get filename from user */ scanf("%s",fname) ; /* open the file */ if ( (in = fopen(fname,"r")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ; }
Example (cont) /* print the contents of the file in uppercase*/ while ( (ch = fgetc(in)) != EOF) /*check for EOF */ printf("%c",toupper(ch)) ; /* close the file */ fclose(in) ; }
Example to write a price list to a file #include <stdio.h> #include <stdlib.h> int main(void) { char fname[40] ; /* file name */ int j ; /* loop counter */ float price[ ] = {39.95, 3.22,1.03} ; /* list of prices */ FILE *out ; /*declare the output file pointer */ /* get the filename from the user */ printf("Enter the filename ") ; scanf("%s",fname) ;
Example (cont) /* open the file */ if ( (out = fopen(fname,"w")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ; } /* write the prices to the file */ for (j = 0 ; j < 3; j++) fprintf(out, "%g",price[j]) ; /* close the file */ fclose(out) ; }
Binary Files • Text files contain bytes that contains ASCII Values. Text files contain human readable information. • Binary files contain bytes that are between 0 and 255. Binary files typically are executables, wav files, picture formats, mp3, mpegs etc. There area a lot of proprietary formats that are binary. • Binary files do not have an EOF character (marker) since the EOF is equally likely to occur as part of the binary data as any other value. • The OS stores the filesize as part of its File Allocation Tables (FAT / inode). • Therefore you must use feof() to determine when the end of file has been reached.
Binary Files • For binary files, you should only use fgetc() to read the binary character. • Other reading functions eg fscanf() are designed only to work with text files. • For binary files, you should only use fputc() to write the binary character. • Other writing functions eg fprintf() are designed only to work with text files.
Reading Files • The basic sequence for reading a binary file is declare file pointer open the file WHILE (NOT feof() ) • read the byte from the file using fgetc(fp) • process the data close the file
Writing Files • The basic sequence for writing a binary file is declare file pointer open the file • write the byte to the file using fputc() close the file
Example to read binary and display in hex #include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(void) { char fname[40] ; /* file name */ unsigned char ch ; /* character to read*/ FILE *in ; /* declare the input file pointer */ printf("Enter the filename ") ; /* get the filename from the user */ scanf("%s",fname) ; /* open the binary file for read*/ if ( (in = fopen(fname,"rb")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ; }
Example /* print the contents of the file in hexadecimal – space separated*/ while ( !feof(in) ) { /* check for EOF */ ch = fgetc(in); printf("%x ",ch) ; } /* new line */ printf("\n") ; /* close the file */ fclose(in) ; }