1 / 37

File Processing : Reading & Writing Strings

File Processing : Reading & Writing Strings. Sring Output : fputs(). fputs() function write a null-terminated string to a specified file. it outputs a string to a stream. Does not write the terminating null character, and return EOF if an error accurs.

silas
Download Presentation

File Processing : Reading & Writing Strings

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. File Processing : Reading & Writing Strings

  2. Sring Output : fputs() • fputs() function write a null-terminated string to a specified file. • it outputs a string to a stream. • Does not write the terminating null character, and return EOF if an error accurs. • Takes 2 parameters : a pointerto the string to be written, and a file pointer.

  3. Example… fputs(“This is a String” , fptr); writes the string “ This is a string” to an opened file indicated by the file pointer fptr. Notes fputs() does not write the ‘\0’ character at the end of the string.The entire file will contain a sequence of characters with no end-of-the-string indicator

  4. String Input:fgets() • reads a string from a specified file. • it gets a string from stream. • It reads until either a new line character is read or the length of the string is less than the specified maximum number of character. • Takes 3 parameter: address where the string is stored, maximum length of the string and a file pointer.

  5. Example.. Char string [81]; fgets (string, 80, fptr); • reads a string, maximum length of eighty characters, from a file indicated by fptr, and stores it into where string is pointing to. Notes Unlike the gets() function, the fgets() function reads the new-line and the newline character remains at the end of the string.

  6. Program Example Part 1/2 /* This program shows the file processing, open, write/read and close file operations. */ # include <stdio.h> /* including the stdio library */ # include <stdlib.h> /* for exit ( ) */ #include <string.h> /* for strlen ( ) */ int main ( ) { FILE * fptr ; /* declare a file pointer */ char string [81] ; puts( "Enter what you want to save in a file." ); /* prompt message */ puts( "End each line with a Return key." ) ; puts( "Enter a Return key at the beginning of the line to END your input:" ); /* open file for write and read, and check for the file error */ if ( ( fptr = fopen ( "textfile.txt", "w+" ) ) == NULL )/* check for error */ { printf ( " Failed to open file: textfile.txt\n" ); /* error message */ exit ( 1 ) ; /* exit program */ }

  7. Program Example Part 2/2 /* read strings from the key board */ while ( ( strlen ( gets ( string ) ) ) > 0 ) /* read a string */ { strcat ( string, "\n" );/* add the new line character to the end of the string */ fputs ( string, fptr );/* write it to a file indicated by fptr */ } rewind ( fptr ) ; /* reset the file to its beginning */ puts ( "The contents of the file text.txt is: " ); /* title message */ while ( ( fgets ( string, 80, fptr ) ) != NULL ) printf ( "%s", string ); /* display string */ fclose ( fptr); /* close the file indicated by fptr */ return 0 ; }

  8. Reading and Writing Formatted Data

  9. Formatted Output:fprintf() • writes formatted data to a file indicated by the file pointer. • it writes formatted output to stream. Example • if fptr contains the file pointer returned by a call to fopen(), then the statement fprintf (fptr, ‘%s%d%.2f”, “Mustang”, 1966, 28000.0000); writes the string Mustang, the integer number 1966, and the real number 28000.00 to the file indicated by the file pointer fptr

  10. Notes • The fprint() function returns the number of bytes in outputted string. • In the event of an error it returns EOF signal. • Like the function printf(), there must be the same number of format specifiers as argument.

  11. Reading Formatted Data from a File

  12. fscanf() • fscanf() function reads input fields from stream. • Each field is formatted according to its format specifier. • fscanf() stores the formatted input at an address passed to its as an argument

  13. Example • Example, if fptr contains the file pointer returned by a call to fopen(), then the statement fscanf(fptr, “%s%d%f”,string,&Inum,&Fnum); reads a string, an integer number, and a real number from a file indicated by the file pointer variable fptr, and stores them at the addresses represented by string, &Inum, and &Fnum, respectively.

  14. Notes • fscanf() returns the number of input fields successfully scanned(read), converted, and stored. The return value does not include scanned fileds that were not stored. • If fscanf() attempts to read at end of file, the return valus is EOF. If no fileds were stored, the return value is 0. • The number of format specifiers and addresses must be the same as the number of input fileds

  15. Standard Streams • Standard Input/Output Streams

  16. Example fprint ( fptr, “Hi”); writes the string “ Hi” to the file indicated by the file pointer fptr. Using the standard file pointer stdout instead of the fptr, fprint(stdout, “Hi”); displays the string “ Hi” on the screen.

  17. Console and File I/O Comparison /*Console I/O Version*/ /*file system I/O version*/ printf(“Hi”); fprintf(stdout, “Hi”); Scanf(“%d”, &Inum); fscanf(stdin,”%d”, &Inum); puts(“Go Home”); fputs(stout, “Go Home”); gets(string); fgets(stdin, string);

  18. Program Example Part 1/2 /* This program shows the file processing, open, write/read format-ted data, and close file operations. Also standard file pointers are used for displaying messages.*/ # include <stdio.h> /* include the stdio library */ # include <stdlib.h> /* include the stdlib.h for the exit ( ) function */ int main ( ) { FILE * fptr ; /* declare a file pointer */ char model [ 30 ], year [ 20 ], price [ 20 ] ; /* declare string storage */ int i ; /* open file for write and read, and check for the file error */ if ( ( fptr = fopen ( "textfile.txt", "w+" ) ) == NULL ) /* check for error */ { fprintf ( stderr, "Failed to open file: textfile.txt\n" ) ; /* error message */ exit ( 1 ) ; /* exit program */ }

  19. Program Example 2/2 /* write formatted data to the file */ fprintf ( fptr, "%10s %6d $%.2f\n", "Mustang", 1966, 28000.0000 ) ; fprintf ( fptr, "%10s %6d $%.2f\n", "WV", 1966, 12000.0000 ) ; fprintf ( fptr, "%10s %6d $%.2f\n", "BMW", 1966, 25000.0000 ) ; rewind ( fptr ) ; /* reset the file to its beginning */ fputs ( "The contents of the file textfile.txt is:\n ", stdout ) ; /* title message */ for ( i = 0 ; i < 3 ; ++i ) /* read three set of data items */ { fscanf ( fptr, "%s %s %s", model, year, price ) ; /*read from file */ fprintf ( stdout, " %10s %6s %12s \n", model, year, price ) ; /* display */ } fclose ( fptr ) ; /* close the file indicated by fptr */ return 0 ; }

  20. 01000000 00000000 00110100 00110001 00110110 00110101 00111000 The binary and Text Representation of a number int n = 16384 ; /* stores 16384 as a binary number in 2 bytes*/ fprintf(fptr,”%d”, n);/* write the binary code for chac ‘1’,’6’,’3’,’8’,’4’ to the file taking 5 bytes*/

  21. Block Input/Output • Binary File Open Mode values

  22. Block Output:fwrite() • This function writes the specified number of bytes(blocks/records) to a file that is opened in binary mode and identified by the file pointer. Example FILE * ftpr; int Inum = 10; /* declare a FILE pointer*/ float Fnum = 1234.56; /* an int number */ long lnum = 123456L; /* a long int number*/ fptr = fopen(“test.bin”,”wb”); /* open test.bin for write in binary mode*/

  23. Exmples fwrite(&Inum, sizeof(int), 1, fptr); fwrite(&Inum, sizeof(float), 1, fptr); fwrite(&Inum, sizeof(long), 1, fptr); • writes the variables Inum, Fnum, and Lnum to test. bin that is identified by the file pointer fptr.

  24. Function fwrite() 1. What to write 2. How many bytes in each block fwrite(&Inum, sizeof(int), 1, fptr); 4. Where to write to 3. How many blocks to write

  25. Block Input:fread() This function reads a specified number of bytes(blocks/records) from a file that is opened in binary mode. Example FILE *fptr; int Inum; /*declare a FILE pointer & int variable*/ float Fnum; /* a floating point variable r*/ long Lnum; /* a long int variable */ fptr = fopen(“test.bin”,”rb”); /* open test.bin for read in binary mode*/

  26. Example fread(&Inum, sizeof(int),1, fptr); fread(&Inum, sizeof(float),1, fptr); fread(&Inum, sizeof(long),1, fptr); reads from test.bin file that is idetified by the file pointer fptr, and store values in variables Inum, Fnum, and Lnum, respectively

  27. The function fread() in Action 1. What to store 2. How many bytes in each block fread(&Inum, sizeof(int), 1, fptr); 4. Where to read 3. How many blocks to read

  28. Program Example Part 1/3 /*This program shows the block I/O operations. It reads and writes an array to a disk file. */ # include <stdio.h> /* including the stdio library */ # include <stdlib.h> int main( ) { /* declaring variables */ FILE * fp ; /* declaring a FILE pointer */ long ArrayOne [10] ; /* declaring an array of long int type */ long ArrayTwo [10] ; /* declaring an array of long int type */ long initializer = 65000L ; /* value used to initialize the array */ int i ; /* loop counter */

  29. Program Example Part 2/3 /* initializing one of our arrays to some large numbers */ for ( i = 0 ; i < 10 ; ++ i, initializer += 100 ) ArrayOne [i] = initializer ; /* opening a file for write/read in binary mode */ if ( ( fp = fopen( "array.bin", "wb+" ) ) == NULL ) { fprintf ( stdout," Failed to open file: array.bin\n" ) ; /* error message */ exit ( 1 ) ; /* exit program */ } /* writing the whole array to array.bin in one statement */ fwrite ( ArrayOne, sizeof ( ArrayOne ), 1, fp ) ; /* reposition the file position indicator to the beginning of the file */ rewind ( fp ) ;

  30. Program Example Part 3/3 /* reading from array.bin file into the second array */ fread ( ArrayTwo, sizeof ( ArrayTwo ), 1, fp ) ; /* closing the file */ fclose ( fp ) ; /* displaying ArrayOne and ArrayTwo */ fprintf ( stdout, "Element # \t ArrayONE \t ArrayTow\n" ) ; fprintf ( stdout, "========\t ========\t =======\n" ) ; for ( i = 0 ; i < 10 ; ++i ) fprintf ( stdout, " %d \t %ld \t %ld \n", i, ArrayOne[i], ArrayTwo[i] ) ; return 0 ; }

  31. Error Handling • The error-handling functions provide facilities to test whether EOF returned by a function indicates an end-of-the-file error or some other error. • feof() • detects end of file on a stream.It return a nonzero if EOF indicator is detected and otherwise int feof (FILE *fpt)

  32. ferror() • tests the given stream for a read or write error. It returns a nonzero value if an error is detected and zero otherwise. int ferror( *fptr) • clearerr() • clears the specified stream error and EOF indicators to 0. void clearerr(FILE *fptr);

  33. RANDOM FILE ACCESS • The c language provides several functions for accessing a file randomly. Each of these functions uses the file position indicator to determine the desired position in the file. Recall that the file position indicator is long int variable that is created by the system when a file is opened.

  34. Random Access:fseek() used to reposition the file reposition the file position indicator associated with an opened file to a new location in the file. fseek(file_pointer, offset, location)

  35. Binary File open Mode Values

  36. File open 0 P U R E C EOF Fseek (fptr, 3L, SEEK_CUR) P U R E C EOF Fseek (fptr, 0L, SEEK_END) 5 EOF P U R E C Fseek (fptr, -2L, SEEK_CUR) 3 P U R E C EOF • Tracing the File Position Indicator start file position indicator text.txt a;command file position indicator text.txt b:command file position indicator text.txt c:command file position indicator text.txt

  37. File Position : ftell() • is type long function that returns the current file position; that is, the value of the file position indicator associated with an opened file. Long ftell(FILE *file_pointer) • Example fseek(ftp, 4L,SEEK_CUR); /*move forward 4 position*/ value=ftell(ftp); /*value is 4*/ fseek(fpt, 0L, SEEK_END); /*move to the end of the file*/ value=ftell(fpt); /*value shows number of bytes in the file*/

More Related