Download presentation
Presentation is loading. Please wait.
Published byMiranda Walton Modified over 8 years ago
1
UniMAP SemI-11/12EKT120: Computer Programming1 Files
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 UniMAP SemI-11/12EKT120: Computer Programming2
3
UniMAP SemI-11/12EKT120: Computer Programming3 Introduction Almost all programs developed before, are interactive. input is entered via keyboard output is via screen or monitor. not suitable if it involves huge amount of input output to be entered or displayed on the screen at one time. Storage of data in variables and arrays is temporary – all data are lost when a program terminates.
4
Solution: file processing UniMAP SemI-11/12EKT120: Computer Programming4
5
A file is a group of related records. * record – is a group of related fields. FILE RECORD What is a FILE? UniMAP SemII-09/10EKT120: Computer Programming5 Field RECORD
6
Files are used for permanent retention of large amounts of data. UniMAP SemII-09/10EKT120: Computer Programming6
7
Steps of Using a File Close file fclose (cPtr); Verify the file is opened successfully if (cPtr == NULL) Initialize and open file cPtr = fopen (“myFile.dat”, mode) ; Declare a file FILE *cPtr; UniMAP SemII-09/10EKT120: Computer Programming7
8
UniMAP SemI-11/12EKT120: Computer Programming8 File Declaration Use #include in your program. Declare a file pointer variable. 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_file and out_file are also known as internal file names.
9
Initializing & Opening a file Before accessing a file, it MUST BE OPENED. UniMAP SemII-09/10EKT120: Computer Programming9 Format: in_filename = fopen (ext_filename, mode); Name used inside a C Program to identify a file A function to open/create file - Is in stdio.h library A function to open/create file - Is in stdio.h library Actual Name of the file used The process to be used on the file
10
Examples of Opening Files FILE *in_file; FILE *out_file; FILE *cPtr; in_file = fopen (“c:data.txt”, “r”); out_file = fopen (“c:results.txt”, “w”); cPtr = fopen (“myFile.dat”, “a”); UniMAP SemII-09/10EKT120: Computer Programming10 declare and initialize the file pointer variables in_file, out_file and cPtr :
11
UniMAP SemI-11/12EKT120: Computer Programming11 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
12
Verifying File Opening Check whether a file has successfully open. It may fail if the particular file does not exist fopen() will return a NULL. Use exit(-1) to stop the program UniMAP SemII-09/10EKT120: Computer Programming12 if (in_file == NULL) { printf(“\nFile fails to open\n”); exit(-1); }
13
UniMAP SemI-11/12EKT120: Computer Programming13 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’
14
UniMAP SemI-11/12EKT120: Computer Programming14 Closing File and fclose function Each opened file needs to be closed. Format: fclose(internal_filename); Examples: fclose(in_file); fclose(out_file);
15
UniMAP SemI-11/12EKT120: Computer Programming15 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)
16
UniMAP SemI-11/12EKT120: Computer Programming16 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);
17
UniMAP SemI-11/12EKT120: Computer Programming17 Reading Data from a Text File Format: fscanf (internal file name, format control string, input list); fscanf(in_file, “%d”, &iMarks); fgetc (internal file name); cCh = fgetc(in_file); ▪ fgets (string variable, size, internal file name); fgets(acName, 10, in_file);
18
UniMAP SemI-11/12EKT120: Computer Programming18 Writing Data to a Text File Format: f printf (internal file name, format control string, output list); fprintf(out_file, “%d”, iMarks); fputc (character expression, internal file name); fputc(cCh, out_file); fputc(“4”, out_file); fputs (string expression, internal file name); fputs(acName, out_file); fputs(“Jane”, out_file);
19
Example Assume: int iA = 100, iB= 400; char cName[30] = “Marion Nasir”; float fX = 34.59; Q: Write iA, iB & cName into the file cPtr. fprintf (cPtr, “\n%d %d %s”, iA, iB, cName); UniMAP SemII-09/10EKT120: Computer Programming19
20
Example 2 Q: Read the book title and year from the user, and then write it in a file cPtr. scanf (“%s %d”, &title, &bYear); fprintf (cPtr, “\n %s %d”, title, bYear); UniMAP SemII-09/10EKT120: Computer Programming20
21
Example 3 Q: Read the cost of an item from the user, and then write it in a file, outFile. scanf (“%f”, &cost); fprintf (outFile, “\n %.2f”, cost); UniMAP SemII-09/10EKT120: Computer Programming21
22
Example 4 Q: Read the book title and year from the the file cPtr. fscanf(cPtr, “%s %d”, &title, &bYear); UniMAP SemII-09/10EKT120: Computer Programming22
23
UniMAP SemI-11/12EKT120: Computer Programming23 Sample Program #include int main(void) { FILE *in_file; FILE *out_file; int iMarks, iTotal = 0, iCount = 0; float fAvg; in_file = fopen("student.dat", "r"); out_file= fopen("student.out", "w"); if(in_file == NULL) { printf("Error opening file\n"); exit(-1); } while(!feof(in_file)) { fscanf(in_file,"%d",&iMarks); ++iCount; iTotal = iTotal + iMarks; fprintf(out_file, " %d ",iMarks); } fAvg = iTotal /iCount; fprintf(out_file, "\n%.2f\n", fAvg); fclose(in_file); fclose(out_file); return 0; }
24
UniMAP SemI-11/12EKT120: Computer Programming24 Sample Input File and Output File 50 60 70 80 90 44 55 66 77 88 24 56 79 50 77 student.dat 50 60 70 80 90 44 55 66 77 88 24 56 79 50 77 64.00 student.out Input file name Data in input file Output file name Display data in output file
25
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. UniMAP SemI-11/1225EKT120: Computer Programming
26
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. UniMAP SemI-11/1226EKT120: Computer Programming
27
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. UniMAP SemI-11/1227EKT120: Computer Programming
28
Creating a Randomly Accessed File When writing an integer, instead of using fprintf(fPtr, “%d”, iNumber); which could print as few as 1 digit or as many as 11 digits, we can use fwrite(&iNumber, sizeof(int), 1, fPtr); which always writes 4 bytes from variable iNumber to the file represented by fPtr. UniMAP SemI-11/1228EKT120: Computer Programming
29
Creating a Randomly Accessed File fread is used to read 4 bytes integer into variable number. The fread and fwrite functions 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. UniMAP SemI-11/1229EKT120: Computer Programming
30
Creating a Randomly Accessed File – Example #include struct clientData { int iAcctNum; char acLastName[15]; char acFirstName[15]; float fBalance; }; int main() { int iIndex; struct clientData sBlankClient = {0, “ “, “ “, 0.0}; FILE *cfPtr; if((cfPtr = fopen(“credit.txt”, “w”)) = = NULL) printf(“file cant be open”); else{ for (iIndex= 1; iIndex<=100; iIndex++) fwrite(&sBlankClient, sizeof(struct ClientData), 1, cfPtr); fclose(cfPtr); } return 0; } 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 30
31
Writing Data Randomly to a Randomly Accessed File #include struct clientData { int iAcctNum; char acLastName[15]; char acFirstName[15]; float bBalance; }; int main () { FILE *cfPtr; struct clientData sClient; if ((cfPtr = fopen(“credit.txt”, “r+”))==NULL) printf(“file cant be open”); else { print(“Enter account number(0 to end input): ”); scanf(“%d”, &sClient.iAcctNum); while (sClient.iAcctNum != 0) { printf(“Enter lastname, firstname, balance”); scanf(“%s %s %f, &sClient.acLastName, &sClient.acFirstName, &sClient.fBalance); fseek(cfPtr, (sClient.iAcctNum – 1) * sizeof(struct clientData), SEEK_SET); fwrite(&sClient, sizeof(struct clientData), 1, cfPtr); printf(“Enter account number”); scanf(“%d”, &sClient.iAcctNum); } //end of while statements } //end of else statements fclose(cfPtr); return 0; } //end of main 31
32
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 UniMAP SemI-11/1232EKT120: Computer Programming
33
Writing Data Randomly to a Randomly Accessed File The statement fseek(cfPtr,(sClient.iAcctNum–1) *sizeof(struct clientData),SEEK_SET); positions the file position pointer for the file reference by cfPtr to the byte location calculated by (iAccountNum-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). UniMAP SemI-11/1233EKT120: Computer Programming
34
Reading Data Randomly from a Randomly Accessed File #include struct clientData { int iAcctNum; char acLastName[15]; char acFirstName[15]; float fBalance; }; int main () { FILE *cfPtr; struct clientData sClient; 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(&sClient, sizeof(struct clientData), 1, cfPtr); if (sClient.iAcctNum != 0) printf(“(“%-6s%-16s%-11s%10.2f\n”,”sClient.iAcctNum, sClient.acLastName, sClient.acFirstName, sClient.fBalance); }} fclose (cfPtr); return 0; } 34
35
Reading Data Randomly from a Randomly Accessed File Output: AcctLast NameFirst NameBalance 29 BrownNancy-24.54 30DunnStacey314.33 31BarkerDoug0.00 fread(&sClient, 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 sClient. UniMAP SemI-11/1235EKT120: Computer Programming
36
THANK YOU UniMAP SemI-11/1236EKT120: Computer Programming
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.