text files
play

Text Files COMP 1002/1402 Purpose Program is in memory What - PDF document

Text Files COMP 1002/1402 Purpose Program is in memory What happens if the computer fails Computation has finished, whats next? User interaction is on line Can we keep a record of it? Does the user need to reinsert


  1. Text Files COMP 1002/1402 Purpose • Program is in memory – What happens if the computer fails – Computation has finished, what’s next? • User interaction is on line – Can we keep a record of it? – Does the user need to reinsert all the data? 1

  2. Storing in Files • Permanent storage – Archiving – User preferences – Record keeping • Intermediate results – Visualization – Check points (30 hours computation) File Types C has two main types: • Binary Files - Everything stored as 0’s and 1’s • Text Files - Usually human readable characters - Each data line ends with newline char 2

  3. Types of files • Binary files • Text files – Store the data in machine representation – Store the data in readable ascii (e.g., a long integer will be stored as 4 format usually a single byte bytes regardless of value). – Sequential access Pros • • Pros – Random access to data – Fast – Good for text – Read/write whole records – Readable (see what is stored) – Easy to navigate (random access) – Data can be recovered – good for all data – High compression ratio • Cons • Cons – Storage space • Low compression ratio – Slow • Hard to recover data – Sequential access • Low compression ratio – Every field of data must be written • Reading through a special program – Hard to navigate File Storage & Access Files are stored in auxiliary storage devices Read and Write access is buffered • A buffer is a storage area • It is temporary 3

  4. Streams File Input and Output is done : • Element by element • Essentially a stream of information • All File structures are byte streams in C. A FILE FILE is the type we use to reference “files” • Defined in stdio.h • Usually declare variable as a pointer: FILE *filename; 4

  5. Standard Files Stdio.h defines 3 standard streams (files) • Standard Input (stdin) • Standard Output (stdout) • Standard Error (stderr) The Standard Files 5

  6. User Files (last) Standard Files are opened automatically User files must be opened by the user • Can be opened for input or output • One file one stream (or vice versa) User Files 6

  7. Opening a File : fopen Useage : fopen("filename","mode"); • Returns a pointer to FILE, a Physical file • Automatically creates buffer Mode Meaning Open file for reading r •If file exists, the marker is positioned at beginning Open text file for writing w •If file exists, it is emptied. Beware !!! •If file doesn’t exist, it is created. Open text file for append a •If file exists, the marker is positioned at end. •If file doesn’t exist, it is created. 7

  8. Examples : Opening files FILE *fpTemp; fpTemp = fopen(“/tmp/TEMPS.DAT","w"); fpTemp = fopen(“C:\\TEMPS.DAT","w"); Returns NULL if there is a problem if((fpTemp=fopen("T.DAT","w"))==NULL){ … Closing a file : fclose Usage fclose(fpTemp); • Returns EOF (end of file constant) if an error occurs if(fclose(fpTemp) == EOF) { … 8

  9. #include <stdio.h> int main() { FILE *fid; char filename[200]; printf(“opening class file\n”); sprintf(filename,”classfile.txt”); fid = fopen(“classfile.txt", “a”); // open in a read only mode if (fid == NULL) { printf(“could not open the file \n”); } else { // process the file . . . } printf(“closing the file \n“); rc = flocse(fid); if (rc == EOF) { printf(“error when closing the file \n”); } return 0; } Checking if a file exists #include <stdio.h> • Why do it? int main() – Warn the user that the file is { about to be erased FILE *fid = NULL; – Ask the user to locate the file if fid = fopen(“file.txt”, “r”) it not there if (fid == NULL) { /* file does not exist decide what to do; */ } else { // file exist // decide what to do … } return 0; } 9

  10. Closing a number of files #include <stdio.h> FILE *fp1, *fp2; void main( void ) { int numclosed = 0; /* Open for read (will fail if file “myfile" does not exist) */ if ((fp1= fopen( “myfile", "r" )) == NULL ) printf( “File ‘myfile’ is not open\n" ); else printf( “File ‘myfile' is open\n" ); /* Open for read/write */ if ((fp2 = fopen( “anotherfile", "w+" )) == NULL ) printf( “File ‘anotherfile' is not open\n" ); else printf( "The file ‘anotherfile' is open\n" ); /* Close stream */ if( fclose(fp1) == EOF ) printf( "The file 'data' was not closed\n" ); /* All other files are closed: */ fcloseall( ); /*printf( "Number of files closed by _fcloseall: %d\n", numclosed ); */ } Reopening/redirecting a file • FILE *freopen(char *filename, char *mode, FILE *fid); • Opens the file “filename” and associates it with stream. • It returns a handle to the newly opened file • Usually used to redirect output to a file (e.g., Stderr); 10

  11. Reopening/redirecting a file #include <stdio.h> #include <stdlib.h> FILE *fp1; void main( void ) { /* Reassign "stderr" to "freopen.out": */ fp1 = freopen( "freopen.out", "w", stderr ); if( stream == NULL ) fprintf( stdout, "error on freopen\n" ); else { fprintf( fp1,"This will go to the file 'freopen.out'\n" ); fprintf( stdout, "successfully reassigned\n" ); fclose(fd1); } system( "type freopen.out" ); } Formatting Input/Output Format Strings (printf, scanf,…) are important To format Strings we must specify: • White space • Text characters • Field Specifiers ( %… ) 11

  12. Whitespace Input One or more whitespace chars: Discard one or more whitespace chars Output Whitespace copied to output Text Characters Input and Output : Exact Matching (Input) or Copy to Output 12

  13. Field Specifiers : Format scanf printf Flag Size Codes Usage Flag Size Codes +- d short int d h h +- int 0 long int sp l l +- u unsigned short int u h +- h 0 unsigned int Sp unsigned long int l l +- h o short int – octal +- h o 0 int – octal sp l long int – octal l 13

  14. scanf printf Flag Size Codes Usage Flag Size Codes +- x X short int – hex x X h h +- int – hex 0 long int – hex sp l l f float f l double l long double L L e, E float - scientific e, E g, G g, G l double – scientific l L long double – L scientific scanf printf Flag Size Codes Usage Flag Size Codes c char c s string s p pointer (address) p h n short – I/O count n int – I/O count l long – I/O count l […] 14

  15. scanf and fscanf scanf("format string", addresses); FILE *fp; fscanf(fp,"format string",addresses); Each function: Side effects & moves file pointer appropriately Return value to be used. Formatting : Input Data Conversion processes characters until: 1. End-of-file is reached 2. Finds an inappropriate character 3. The number of characters read is equal to maximum field width 15

  16. scanf & fscanf Return Value Returns (next slide) • EOF if End-of-File is reached • or Number of successful conversions 16

  17. fscanf examples printf("format string", variables); FILE *fptemp; fprintf(fptemp,"format",variables); 17

  18. fprintf : Return Value Be certain to check for errors if (fprintf(fp, "%s", str) < 0) {…} The error check is important !!! Character Input/Output int getchar(void); /* think as if “scanf” with %c */ a = getchar(); /* buffered input same as %c */ int putchar(int out_char); /* think printf %c */ Always returns the outputted character 18

  19. User-File Character Input/Output int getc(FILE *fpIn); int fgetc(FILE *fpIn); Each get a character from the FILE *fpIn Returning it in integer form (EOF) on errors User-File Character Input/Output int putc(int oneChar, FILE *fpOut); int fputc(int oneChar, FILE *fpOut); Output a single character Return the character if successful ; else EOF 19

  20. User-File Character Input/Output int ungetc(int oneChar, FILE *stream); Returns oneChar if successful Attempts to put oneChar back into Stream Copying a file • #include <stdio.h> • #include <stdlib.h> • … 20

  21. Error checking • ferror(FILE *fid) – Checks if the error flag is set for the file • fclear(FILE *fid) – Clears the error flag associated with the file • feof(FILE *fid) – Checks if end of file was reached Binary files • A permanent storage of data which is kept in the format of the hardware. • A “mirror” image of the memory of the computer • Purpose – Provide a copy of the memory for later usage – Transferring data from one program to another Open the file – Recovery in cases where computation has failed (checkpoints). 21

Recommend


More recommend