1 / 29

Files

Files. Outline. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access Files. Introduction. Almost all programs developed before, are interactive.

Download Presentation

Files

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. Files EKT120: Computer Programming

  2. Outline • Introduction • File Declaration and Initialization • Creating and Opening File • Closing File • EOF • Reading from and Writing into a File • Extra : Random Access Files EKT120: Computer Programming

  3. Introduction • Almost all programs developed before, are interactive. • In interactive environment, input is entered via keyboard and output is via screen or monitor. • This type of processing is not suitable if it involves huge amount of input or output to be entered or displayed on the screen at one time. • Therefore, file processing can solve the problem mentioned. EKT120: Computer Programming

  4. Storage of data in variables and arrays is temporary – all data are lost when a program terminates. • Files are used for permanent retention of large amounts of data. • A file is a group of related records. * record – is a group of related fields. EKT120: Computer Programming

  5. File Declaration • To implement file processing in C, it is advisable to include #include <stdlib.h> in your program. • To use file for input and output, a file pointer variable has to be declared. FILE *in_file; => in_file is a pointer to a FILE structure FILE *out_file; =>out_file is a pointer to a FILE structure • in_fileandout_file are also known as internal file names. EKT120: Computer Programming

  6. File Initialization • File pointer initialization has the following format : internal_filename =fopen(external_filename, mode); For example, to declare and initialize the file pointer variables in_file and out_file: FILE *in_file; FILE *out_file; in_file = fopen (“c:data.txt”, “r”); out_file = fopen (“c:results.txt”, “w”); mode external file name

  7. Opening File and fopen function • Format: internal_filename =fopen(external_filename, mode); • Each file must be opened before it can be accessed or processed. • When opening a file, external file name needs to be related to the internal file name using fopen function. • fopenis the stdio library function used to open or create a file. • Internal file name is the name that the C system uses to identify a file among others that a program might process. • External file name is the name given at “save file as” outside the program e.g. “student.dat”, “records.out”, “data.txt”, etc. • Mode is to indicate the process to be made onto a file.

  8. File Modes • Basics mode are: • “r” : open file to read • “w” : open file to write • “a” : append data to the end of an already existing file • “r+” : open and create file for update, i.e. read and write, does not overwrite previous contents • “w+” : open and create file for update, overwrite • “a+” : append, open or create file for update EKT120: Computer Programming

  9. File Opening Verification • There is a possibility of a file fails to open. Could be the particular file does not exist. • Therefore, need to check or verify whether the file is successfully opened. • If file fails to open, need to stop the program, use exit(-1).A file pointer whose value equals to NULL(empty or ‘0’)is called a null pointer. if (in_file == NULL) { printf(“\nFile fails to open\n”); exit(-1); } EKT120: Computer Programming

  10. File Opening Verification • You can also combine file initialization and file opening verification, using statement: if ((in_file = fopen(“student.dat”, “r”)) == NULL) { printf(“\nFile fails to open\n”); exit(-1); } * NULL = empty or ‘0’ EKT120: Computer Programming

  11. Closing File and fclose function • Each opened file needs to be closed. • Format: fclose(internal_filename); Examples: fclose(in_file); fclose(out_file); EKT120: Computer Programming

  12. End-of-File (EOF) and feof function • Usually you don’t know how many data you want to read from file. • Therefore, need to check whether you have reached end of file. • End-of-file (EOF) character marks the end of the entire file. Function feof is used to detect EOF. • Format: feof(internal_filename) EKT120: Computer Programming

  13. Example for EOF and feof function FILE *in_file; in_file = fopen(“student.dat”, “r”); if(in_file == NULL) { printf(“Error opening file\n”); exit(-1); } while(!feof(in_file)) { //statements to process data } fclose(in_file); EKT120: Computer Programming

  14. Reading Data from a Text File • Format: • fscanf (internal file name, format control string, input list); fscanf(in_file, “%d”, &marks); • fgetc (internal file name); ch = fgetc(in_file); ▪fgets (string variable, size, internal file name); fgets(name, 10, in_file); EKT120: Computer Programming

  15. Writing Data to a Text File • Format: • fprintf (internal file name, format control string, output list); fprintf(out_file, “%d”, marks); • fputc (character expression, internal file name); fputc(ch, out_file); fputc(“4”, out_file); • fputs (string expression, internal file name); fputs(name, out_file); fputs(“Jane”, out_file); EKT120: Computer Programming

  16. Sample Program while(!feof(in_file)) { fscanf(in_file,"%d",&marks); ++count; total = total + marks; fprintf(out_file, " %d ",marks); } avg = total /count; fprintf(out_file, "\n%.2f\n", avg); fclose(in_file); fclose(out_file); return 0; } #include <stdio.h> #include <stdlib.h> int main(void) { FILE *in_file; FILE *out_file; int marks, total = 0, count = 0; float avg; in_file = fopen("student.dat", "r"); out_file= fopen("student.out", "w"); if(in_file == NULL) { printf("Error opening file\n"); exit(-1); } EKT120: Computer Programming

  17. Sample Input File and Output File 50 60 70 80 90 44 55 66 77 88 24 56 79 50 77 Input file name student.dat Data in input file Output file name student.out Display data in output file 50 60 70 80 90 44 55 66 77 88 24 56 79 50 77 64.00 EKT120: Computer Programming

  18. Random Access Files • In sequential access file, records in a file created with the formatted output function fprintf are not necessarily the same length. • Individual records of a random access file are normally fixed in length. • This record can be accessed directly without searching through other records. Thus, file searching process will be faster. • Random access is suitable to be used in large database systems such as in airline reservation systems, banking systems and other kind of transaction processing systems. EKT120: Computer Programming

  19. Random Access File • Because every record in randomly access file normally fixed in length, data can be inserted in random access file without destroying other data. • Data stored previously can also be updated or deleted without rewriting the entire file. EKT120: Computer Programming

  20. Creating a Randomly Accessed File • Function fwrite is used to transfer a specified numbers of byte beginning at a specified location in memory into a file. • The data is written beginning at the location in the file indicated by the file position pointer. • Function fread transfers a specified number of bytes from the file specified by the file position to an area in memory with a specified address. EKT120: Computer Programming

  21. Creating a Randomly Accessed File • When writing an integer, instead of using fprintf(fPtr, “%d”, number); which could print as few as 1 digit or as many as 11 digits, we can use fwrite(&number, sizeof(int), 1, fPtr); which always writes 4 bytes from variable number to the file represented by fPtr. EKT120: Computer Programming

  22. Creating a Randomly Accessed File • fread is used to read 4 bytes integer into variable number. • The fread and fwritefunctions are capable of reading and writing arrays of data to and from a disk. • The third argument in the fread and fwrite is the number of element in array that should be read from disk or written to disk. • The preceding fwrite function call, writes a single integer to disk, so third argument is 1. • File processing program rarely writes a single field to a file. Normally, we write one struct at a time. EKT120: Computer Programming

  23. Creating a Randomly Accessed File – Example This program shows how to open a randomly access file, define a record format using structure, write a data to disk, and close the file. This program initializes all 100 records of a file “credit.txt” with empty struct using function fwrite #include <stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[15]; float balance; }; int main(){ int i; struct clientData blankClient = {0, “ “, “ “, 0.0}; FILE *cfPtr; if((cfPtr = fopen(“credit.txt”, “w”)) = = NULL) printf(“file cant be open”); else{ for (I = 1; i<=100; i++) fwrite(&blankClient, sizeof(struct ClientData), 1, cfPtr); fclose(cfPtr); } return 0; }

  24. Writing Data Randomly to a Randomly Accessed File #include <stdio.h> #include <stdlib.h> struct clientData { int acctNum; char lastName[15]; char firstName[15]; float balance; }; int main () { FILE *cfPtr; struct clientData client; if ((cfPtr = fopen(“credit.txt”, “r+”))==NULL) printf(“file cant be open”); else { print(“Enter account number(0 to end input): ”); scanf(“%d”, &client.acctNum); while (client.acctNum != 0) { printf(“Enter lastname, firstname, balance”); scanf(“%s %s %f, &client.lastName, &client.firstName, &client.balance); fseek(cfPtr, (client.acctNum – 1) * sizeof(structclientData), SEEK_SET); fwrite(&client, sizeof(structclientData), 1, cfPtr); printf(“Enter account number”); scanf(“%d”, &client.acctNum); } //end of while statements } //end of else statements fclose(cfPtr); return 0; } //end of main

  25. Writing Data Randomly to a Randomly Accessed File • Output: Enter account number (0 to end) ? 29 Enter lastname, firstname, balance ?Brown Nancy -24.54 Enter account number (0 to end) ? 30 Enter lastname, firstname, balance ?Dunn Stacy 314.33 Enter account number (0 to end) ? 31 Enter lastname, firstname, balance ?Barker Doug 0.00 Enter account number (0 to end) ? 0 EKT120: Computer Programming

  26. Writing Data Randomly to a Randomly Accessed File • The statement fseek(cfPtr,(client.acctNum–1) *sizeof(struct clientData),SEEK_SET); positions the file position pointer for the file reference by cfPtr to the byte location calculated by (accountNum-1)*sizeof(struct clientData); • Because of the account number is between 1 to 100 but the byte positioning starts from 0, the account number needs to be subtracted with 1 (minus 1). EKT120: Computer Programming

  27. Reading Data Randomly from a Randomly Accessed File #include <stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[15]; float balance; }; int main () { FILE *cfPtr; struct clientData client; if((cfPtr = fopen(“credit.txt”, “r”)) = = NULL) printf(“file cant be open”); else{ printf(“%-6s%-16s%-11s%10s\n”, “Acct”, “Last Name”, “ First Name”, “Balance”); while (!feof(cfPtr)) { fread(&client, sizeof(struct clientData), 1, cfPtr); if (client.acctNum != 0) printf(“(“%-6s%-16s%-11s%10.2f\n”,”client.acctNum, client.lastName, client.firstName, client.balance); }} fclose (cfPtr); return 0; }

  28. Reading Data Randomly from a Randomly Accessed File • Output: • Acct Last Name First Name Balance • Brown Nancy -24.54 • 30 Dunn Stacey 314.33 • 31 Barker Doug 0.00 fread(&client, sizeof(struct clientData), 1, cfPtr); Reads the number of bytes determined by sizeof(struct clientData) from the file reference by cfPtr and stores the data in the structure client. EKT120: Computer Programming

  29. THANK YOU EKT120: Computer Programming

More Related