340 likes | 471 Views
Welcome to Group 2 Presentation of: EOF & Fseek() by: Alejandro Burtrago Carlos Lopez Robert Seonarain Shain Leonard Tony Ortega. End Of File. General Objective Description:
E N D
Welcome to Group 2 Presentationof:EOF & Fseek()by:Alejandro BurtragoCarlos LopezRobert SeonarainShain LeonardTony Ortega
General Objective Description: The End of File program is designed to open a user specified text file to read and display it line by line until the end of file is reached.
Outline: • Define • Create Variables • User Interface Getting File Name • Open File Display Error if Applicable • While Not At End of File Read a Line and Display It.
Code: Create Variable: char buf[BUFSIZE]; char filename[20]; FILE *fp;
Code: User Interface: puts("Enter name of text file to display: "); gets(filename);
Functions: puts(): The function puts() writes str to stdout, then writes a newline character. puts() returns non-negative on success, or EOF on failure. gets(): reads characters from stdin and loads them into str, until a newline or EOF is reached. The newline character is translated into a null termination. The return value of gets() is the read-in string, or NULL if there is an error.
Code: Open File: if ( (fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Error opening file."); exit(1); }
Functions: fopen(): The fopen() function opens a file indicated by fname and returns a stream associated with that file. mode is used to determine how the file will be treated (i.e. for input, output, etc). fprintf(): The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() a far as the format goes. The return value of fprintf() is the number of characters outputted, or a negative number if an error occurs.
Code: Read and Display: while ( !feof(fp) ) { fgets(buf, BUFSIZE, fp); printf("%s",buf); } fclose(fp);
Functions: feof(): The function feof() returns a nonzero value if the end of the given file stream has been reached. fgets(): The function fgets() reads up to num - 1 characters from the given file stream and dumps them into str. The string that fgets() produces is always NULL- terminated. fgets() will stop when it reaches the end of a line, in which case str will contain that newline character. Otherwise, fgets() will stop when it reaches num - 1 characters or encounters the EOF character. fgets() returns str on success, and NULL on an error.
File Function Program Random access with fseek()
Create file Write to file Read file Seek file element Print element
I/O functions • fprintf(), prototype int fprintf(FILE *stream, const char *format,…);, ouputs the values of the argument list as specified in the format string to the stream pointed to by file stream • fopen(), prototype FILE *fopen(const char *fname, const char *mode);, opens a file whose name is pointed to by fname and returns the stream that is associated with it with the allowable operations defined by the value of mode • fwrite(), prototype size_t fwrite(const void *buf, size_t size, size_t count, FILE *stream);, writes count number of objects, each object size bytes in length, to the stream pointed to by file stream from the character array pointed to by buf
I/O functions cont’d • fseek(), prototype int fseek(FILE *stream, long int offset, int origin);, sets the file position indicator associated with file stream according to the values of offset and origin and supports random access I/O operations • Values for origin must be one of the 3 following macros • SEEK_SET: seek from start of file • SEEK_CUR: seek from current position • SEEK_END: seek from end of file • Return value of 0 implies success, nonzero value indicates failure • fread(), prototype size_t fread(void *buf, size_t size, size_t count, FILE *stream);, reads count number of objects size bytes in length from the stream pointed to by file stream and stores them in the array pointed to by buf
Explanation of our Example ProgramRandom access with fseek()
Initialize array • for(int count=0;count<MAX;count++) array[count]=count*10 • Array elements 0 through 49 will be initialized as (0x10) though (49x10)
Open binary file for writing if ( (fp = fopen("RANDOM.DAT", "wb")) == NULL) { fprintf(stderr, "\nError opening file."); exit(1); } • fopen() will open the file random.dat for binary writing operations • If the if statement reads a null (0) value if will print “error opening file” into random.dat
Write array to file if ( (fwrite(array, sizeof(int), MAX, fp)) != MAX) { fprintf(stderr, "\nError writing data to file."); exit(1); } fclose(fp); • Fwrite will write MAX (50) objects to the file fp taken from the array; the objects are all 4 bytes in length, taken from the size of an integers byte length • fclose() will close the file and leave it in memory
Open file for reading if ( (fp = fopen("RANDOM.DAT", "rb")) == NULL) { fprintf(stderr, "\nError opening file."); exit(1); } • fopen() will open the recently written and saved file RANDOM.DAT for binary reading operations • If the if statements reads a null (0) value “error opening file” will be printed to RANDOM.DAT
Move position indicator to specified element if ( (fseek(fp, (offset*sizeof(int)), SEEK_SET)) != NULL) { fprintf(stderr, "\nError using fseek()."); exit(1); } • fseek() will set the file position indicator at the start of the file pointer fp and will increment according the 4 byte limit set by size(int) • fseek() returning a 0 value implies success; so fseek() not equaling zero will imply a false value and will force fprintf() to print “error using fseek().” into RANDOM.DAT
Read in a single integer. fread(&data, sizeof(int), 1, fp); • fread() will read 1 item of 4 bytes in length set by sizeof(int) from the file pointer fp and store it into the memory address of the array data
Ask for element to read and display, quit when -1 entered while(1) { printf("\nEnter element to read, 0-%d, -1 to quit: ",MAX-1); scanf("%ld", &offset); if (offset < 0) break; else if (offset > MAX-1) continue; if ( (fseek(fp, (offset*sizeof(int)), SEEK_SET)) != NULL) { fprintf(stderr, "\nError using fseek()."); exit(1); } fread(&data, sizeof(int), 1, fp); printf("\nElement %ld has value %d.", offset, data); } • the while loop will continue to perform the last three functions until the user enters a value, defined by the pointer offset, that is less than 0
The Example Code • /* Random access with fseek(). */ • #include <stdio.h> • #include <stdlib.h> • #include <io.h> • #define MAX 50 • main() • { • FILE *fp; • int data, count, array[MAX]; • long offset; • /* Initialize the array. */ • for (count = 0; count < MAX; count++) • array[count] = count * 10; • /* Open a binary file for writing. */ • if ( (fp = fopen("RANDOM.DAT", "wb")) == NULL) • { • fprintf(stderr, "\nError opening file."); • exit(1); • }
The Example Code • /* Write the array to the file, then close it. */ • if ( (fwrite(array, sizeof(int), MAX, fp)) != MAX) • { • fprintf(stderr, "\nError writing data to file."); • exit(1); • } • fclose(fp); • /* Open the file for reading. */ • if ( (fp = fopen("RANDOM.DAT", "rb")) == NULL) • { • fprintf(stderr, "\nError opening file."); • exit(1); • } • /* Ask user which element to read. Input the element */ • /* and display it, quitting when -1 is entered. */
The Example Code • while (1) • { • printf("\nEnter element to read, 0-%d, -1 to quit: ",MAX-1); • scanf("%ld", &offset); • if (offset < 0) • break; • else if (offset > MAX-1) • continue; • /* Move the position indicator to the specified element. */ • if ( (fseek(fp, (offset*sizeof(int)), SEEK_SET)) != NULL) • { • fprintf(stderr, "\nError using fseek()."); • exit(1); • } • /* Read in a single integer. */ • fread(&data, sizeof(int), 1, fp); • printf("\nElement %ld has value %d.", offset, data); • } • fclose(fp); • }
Another Fseek() Example void PtrSeek(FILE *fptr) { long offset1, offset2, offset3, offset4; offset1 = PtrTell(fptr); DataRead(fptr); offset2 = PtrTell(fptr); DataRead(fptr); offset3 = PtrTell(fptr); DataRead(fptr); offset4 = PtrTell(fptr); DataRead(fptr); printf("\nReread the tesseven.txt, in random order:\n"); // re-read the 2nd line of the tesseven.txt fseek(fptr, offset2, SEEK_SET); DataRead(fptr); // re-read the 1st line of the tesseven.txt fseek(fptr, offset1, SEEK_SET); DataRead(fptr); // re-read the 4th line of the tesseven.txt fseek(fptr, offset4, SEEK_SET); DataRead(fptr); // re-read the 3rd line of the tesseven.txt fseek(fptr, offset3, SEEK_SET); DataRead(fptr); }