1 / 33

Chapter 12: Data Files and File Processing

Chapter 12: Data Files and File Processing. Objectives: You’ll learn about; Introduction Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc() and fputc() Using fread() and fwrite(). Introduction.

elden
Download Presentation

Chapter 12: Data Files and File Processing

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. Chapter 12: Data Files and File Processing Objectives: You’ll learn about; • Introduction • Files and streams • Creating a sequential access file • Reading data from a sequential access file • Using fgetc() and fputc() • Using fread() and fwrite() Chapter 12 : File Processing

  2. Introduction • Storage of data in variables and arrays is temporary-all such data are lost when a program terminates. • Files are used for permanent retention of large amounts of data. • Computers store files on secondary storage devices esp. disk storage devices. • A file is a group of related records. • A record is a group of related fields. Chapter 12 : File Processing

  3. 0 1 2 3 4 5 6 7 8 . . . . . n-1 Files and Streams • C views a file as a sequential stream of bytes. • A file ends either with an EOF (end-of-file) marker or at a specified byte number specified by the system. • When a file is opened, a stream is associated with a file. • Streams provide communication channels between files and the programs. Chapter 12 : File Processing

  4. Files and Streams cont… • In addition to providing access to a file, a stream can also be used to access devices. • For example, when a program (any program) is executed, 3 streams are automatically opened: • standard input (stdin) • enable the program to read data from keyboard • standard output (stdout) • enable the program to print data on the screen • standard error (stderr) • enable program to print errors on the screen • They are all manipulated using file pointers. Chapter 12 : File Processing

  5. Creating a Sequential Access File #include <stdio.h> void main (void) { int account; char name[30]; float balance; FILE *fptr; if ((fptr = fopen("D:/clients.txt", "w")) == NULL) printf("Error: the file cannot be opened\n"); else { printf ("Enter the account #, name and balance or EOF to end input:\n"); scanf ("%d %s %f", &account, name, &balance); while (!feof(stdin)) { fprintf(fptr, "%d %s %.2f\n", account, name, balance); scanf ("%d%s%f", &account, name, &balance); } } fclose (fptr); } Chapter 12 : File Processing

  6. Creating a Sequential Access File cont… • Output from program that creates sequential access file Enter the account #, name and balance or EOF to end input: 111 sara 24.98 222 hannah 345.67 333 ruby 0.00 444 Arris -42.16 555 Nufail 224.62 666 Yasmin 987.90 ^Z Press any key to continue Chapter 12 : File Processing

  7. Creating a Sequential Access File cont… • Content of “D:/client.txt”: Chapter 12 : File Processing

  8. Creating a Sequential Access File cont… • FILE *fptr; • States that f is a pointer to a file structure • If there is more than one file, each file needs to have its own FILE pointer. • if ((fptr = fopen("D:/clients.txt", "w")) == NULL) • The fopen() function takes 2 arguments: the file name and the file mode. • This statement will try to open a file named “clients.txt”. • If the file is to be placed in a different directory than the program directory, the full path need to be specified. For example: “D:/clients.txt” • The function returns a pointer to the successfully opened file. But if the file cannot be opened, a NULL is returned. • The option “w” is the mode of the file to be opened. Chapter 12 : File Processing

  9. Creating a Sequential Access File cont… r - open for reading w - open for writing (file need not exist),if the file already exists, discard current contents a - open for appending (file need not exist), writing at the end of the file. If the file already exists, discard current contents r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists), writing is done at the end of the file Chapter 12 : File Processing

  10. Creating a Sequential Access File cont… • while (!feof(stdin)) • Determines whether the input from the keyboard is an EOF character or not. If it is an EOF character, the while loop will terminate. • An EOF character is not the word “EOF” Chapter 12 : File Processing

  11. Creating a Sequential Access File cont… • fprintf(fptr, "%d %s %.2f\n", account, name, balance); • Writes data to the file clients.dat • Equivalent to printf() except that it receives as an argument a file pointer for the file to which the data will be written. • feof(fptr); • Closes the file “clients.txt”. • Will actually write the data to the file. • If fclose() is not called explicitly, the operating system will close the file when the program terminates. Chapter 12 : File Processing

  12. Creating a Sequential Access File cont… • If an error occurs while opening a file (in which case fopen() returns a NULL), it could be due to any of these errors: • Opening a non-existing file for reading • Opening a file for reading or writing without having granted the appropriate access to the file by the operating system. • Opening a file for writing when no disk space is available. • Always remember that the mode “w” will overwrite the current data in the file. When we want to update a file, always use the update mode r+” (but w/r from top) Chapter 12 : File Processing

  13. Reading Data from a Sequential Access File #include <stdio.h> void main (void) { int account; char name[30]; float balance; FILE *fptr; if ((fptr = fopen("D:/clients.txt", "r")) == NULL) printf("Error: the file cannot be opened\n"); else { printf ("%-10s%-13s%s\n", "Account", "Name", "Balance"); fscanf (fptr, "%d %s %f", &account, name, &balance); while (!feof(fptr)) { printf ("%-10d%-13s%.2f\n", account, name, balance); fscanf (fptr, "%d %s %f", &account, name, &balance); } } fclose (fptr); } Chapter 12 : File Processing

  14. Reading Data from a Sequential Access File cont… • Output from program that reads data from sequential access file Account Name Balance 111 sara 24.98 222 hannah 345.67 333 ruby 0.00 444 Arris -42.16 555 Nufail 224.62 666 Yasmin 987.90 Press any key to continue Chapter 12 : File Processing

  15. Reading Data from a Sequential Access File cont… • if ((fptr = fopen("D:/clients.txt", "r")) == NULL) • Attempts to open the file clients.txt for reading and determines whether the file is opened successfully. Notice that the mode used is “r”. • fscanf (fptr, "%d %s %f", &account, name, &balance); • Reads data from the file clients.txt • Equivalent to function scanf() except that it receives as an argument a file pointer for the file from which the data is read. Chapter 12 : File Processing

  16. Complete credit inquiry program #include<stdio.h> void main() { int request, account; float balance; char name[30]; FILE *fptr; if ((fptr = fopen("D:/clients.txt", "r")) == NULL) printf("Error: the file cannot be opened\n"); else { printf("Enter request\n" "1 - List accounts with zero balances\n" "2 - List accounts with credit balances\n" "3 - List accounts with debit balances\n" "4 - End of run\n? "); scanf("%d", &request); Chapter 12 : File Processing

  17. Complete credit inquiry program cont… while(request!=4) { fscanf (fptr, "%d %s %f", &account, name, &balance); switch(request){ case 1: printf("\nAccounts with zero balances:\n"); while (!feof(fptr)) { if( balance == 0 ) { printf ("%-10d%-13s%.2f\n", account, name, balance); } fscanf (fptr, "%d %s %f", &account, name, &balance); } break; Chapter 12 : File Processing

  18. Complete credit inquiry program cont… case 2: printf("\nAccounts with credit balances:\n"); while (!feof(fptr)) { if( balance < 0 ) { printf ("%-10d%-13s%.2f\n", account, name, balance); } fscanf (fptr, "%d %s %f", &account, name, &balance); } break; Chapter 12 : File Processing

  19. Complete credit inquiry program cont… case 3: printf("\nAccounts with debit balances:\n"); while (!feof(fptr)) { if( balance > 0 ) { printf ("%-10d%-13s%.2f\n", account, name, balance); } fscanf (fptr, "%d %s %f", &account, name, &balance); } break; } /* End while before switch */ Chapter 12 : File Processing

  20. Complete credit inquiry program cont… rewind(fptr); /* return fptr to beginning of file */ printf("\n? "); scanf("%d", &request); } /* End while before switch */ printf("End of run.\n"); fclose(fptr); } /* End else */ } /* End main */ Chapter 12 : File Processing

  21. Output Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run ? 1 Accounts with zero balances: 333 ruby 0.00 Chapter 12 : File Processing

  22. Complete credit inquiry program cont… ? 2 Accounts with credit balances: 444 Arris -42.16 ? 3 Accounts with debit balances: 111 sara 24.98 222 hannah 345.67 555 Nufail 224.62 666 Yasmin 987.90 Chapter 12 : File Processing

  23. Complete credit inquiry program cont… ? 4 End of run. Press any key to continue NOTE : You must create a sequential access file first, then run this complete program to get such output. Chapter 12 : File Processing

  24. Using fgetc() and fputc() • Syntax: • int fgetc(FILE *f) • fputc(int c, FILE *f) • fgetc() reads a character from the file referred to by the file pointer f. • fputc() puts the character c into the file referred to by the file pointer f. • If the file has reached the end, fgetc() will return the EOF character. Chapter 12 : File Processing

  25. Summary Chapter 12 : File Processing

  26. FILES WHY “FILES” ? Data can be permanently stored in magnetic media. Facilitates batch processing. What to learn from FILES topic?  File handling functions and commands.  Text and Binary files processing. Chapter 12 : File Processing

  27. It is necessary to open a file before it can be used for reading or writing. • When a file is no longer in used or access mode is changed (from read to write or append), it should be closed. Opening and Closing Files A file can have one of the following access mode: “r” read only “w” write only “a” append from the end “r+” “w+” read/write from beginning “a+” read and append Chapter 12 : File Processing

  28. FILE VARIABLE DECLARATION TO OPEN A FILE FOR READING: FILE *fopen(const char *path, const char *type); Example in C: FILE *textFile; textFile = fopen(“c:\Cfolder\data.txt”, “r”); TO CLOSE FILES: fclose(filename); Chapter 12 : File Processing

  29. TEXT FILES • A collection of ASCII characters, written in lines and each line contains a specific end-of-line marker. • In the end of the text file there is an end-of-file marker. IMPORTANT!! A text file can be created and viewed using an editor while a binary file CANNOT. A text file can also be created from within a program by writing data (line by line or character by character) to a file that has been declared as text file. Chapter 12 : File Processing

  30. Associated commands are: fputc() -writes a char at a time to a file fputs() -writes a string to a file fprintf() - writes a variable number of items to an output stream fgetc() - reads a char from stream fgets() - reads from stream into array fscanf() - reads a variable number of items from stream feof - tests if file has reaches its end. Chapter 12 : File Processing

  31. A sequence arbitrary bytes of structured data. • Not in human readable form. IMPORTANT!! A BINARY FILE can ONLY be created from within a program. A binary file CANNOT be viewed by an editor. To view the contents of a binary file is to write a program (or subprogram) to read each structure and format them to screen. BINARY FILES Chapter 12 : File Processing

  32. Associated commands are: fread()- reads a specified number of items from the stream fwrite() - writes the specified max number of item to the stream. feof - tests if file has reaches its end. Given these declarations: FILE *data //text file variable FILE *topTen; //random access file infor chart[11]; int position; infor line[1]; Chapter 12 : File Processing

  33. data = fopen(“a:\song.txt”, “r”); topTen = fopen(“c:\Cfolder\pop.bin”, “wb”); fgets(chart[position].record,60,data); fscanf(data, “%d”, &position); fread(line, sizeof(infor), 1, topTen); fwrite(chart, sizeof(infor), 11, topTen); fseek(topTen, (long int) position *sizeof(infor), SEEK_SET); fclose(topTen); Chapter 12 : File Processing

More Related