Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files Programming 1. 2 What is a File? Is a block of arbitrary information, or resource for storing information, which is available to a computer program.

Similar presentations


Presentation on theme: "Files Programming 1. 2 What is a File? Is a block of arbitrary information, or resource for storing information, which is available to a computer program."— Presentation transcript:

1 Files Programming 1

2 2 What is a File? Is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable storage such as the Hard disc. Is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable storage such as the Hard disc.

3 Types of File Text Files Binary Files

4 File Processing For read from or write to a file you should do the following: You MUST open the file and specify the opening mode: read, write, append, … etc. You can perform the required operation (read or write) after that. You have to close the file after you finish the task.

5 File Processing You can declare the file pointer (binary of text) as the following: FILE *f1;  f1 is a pointer You can open the file by the following statement: f1 = fopen(“file path”, “opening mode”); Examples: f1 = fopen (“c:\\myfile.txt”, “rt”);  This opens a Text File with the name “myfile.txt” in the root of drive C for Reading Text data.

6 Modes for opening files The second argument of fopen is the mode in which we open the file. There are three "r" opens a file for reading "w" opens a file for writing - and writes over all previous contents (deletes the file so be careful!) "a" opens a file for appending - writing on the end of the file

7 File Processing Examples (contd.): f1 = fopen (“c:\\myfile.uuu”, “wt”);  This opens a Text File with the name “myfile.uuu” in the root of drive C for Writing Text data. f1 = fopen (“c:\\myfile.xxx”, “rb”);  This opens a Binary File with the name “myfile.xxx” in the root of drive C for Reading Binary data. f1 = fopen (“c:\\myfile.abc”, “wb”);  This opens a Binary File with the name “myfile.abc” in the root of drive C for Writing Binary data.

8 File handling in C In C we use FILE * to represent a pointer to a file. fopen is used to open a file. It returns the special value NULL to indicate that it couldn't open the file. FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { fprintf (stderr, “ERROR”); /* DO SOMETHING */ }

9 File Processing You can use fprintf and fscanf to write to or read from a Text File respectively. You can use fwrite and fread to write to or read from a Binary File respectively. close the file by the following statement: fclose(f1);

10 Text Files Used to store data as text. fprintf is used to write data to a text file. fprintf ([file pointer], [formatting sting], [arg1], [arg2], …) fscanf is used to read data from a text file. fscanf ([file pointer], [formatting sting], [&arg1], [&arg2], …)

11 Writing to a file using fprintf fprintf works just like printf and sprintf except that its first argument is a file pointer. We could also read numbers from a file using fscanf – but there is a better way. FILE *fptr; fptr= fopen ("file.dat","w"); /* Check it's open */ fprintf (fptr,"Hello World!\n");

12 Example 1 void main(void) { FILE *f1; float x=5.346; char cc[] = “Hello”; f1 = fopen(“c:\\abc.txt”, “wt”); fprintf( f1, “%s %f”, cc, x); fclose(f1); }

13 Example 2 void main(void) { FILE *f1; float x; char cc[100]; f1 = fopen(“c:\\abc.txt”, “rt”); fscanf( f1, “%s %f”, cc, &x); fclose(f1); }

14 Example 3 void main(void) { FILE *f1, *f2; char c; f1 = fopen(“c:\\abc.txt”, “rt”); f2 = fopen(“c:\\abc_copy.txt”, “wt”); while(!feof(f1)) { fscanf( f1, “%c”, &c); fprintf( f2, “%c”, c); } fclose(f1); fclose(f2); }

15 Example 4 struct Pers_Data { char Name[100]; int ID; char Add[255]; }; void main(void) { Pers_Data P[10]; FILE *f; int i; for( i = 0; i<10; i++) { scanf(“%s”, P[i].Name); scanf(“%d”, &P[i].ID); scanf(“%s”, P[i].Add); } f = fopen(“c:\\DataBase.1”, “wt”); for( i = 0; i<10; i++) { fprintf(f, “%s”, P[i].Name); fprintf(f, “%d”, P[i].ID); fprintf(f, “%s”, P[i].Add); } }//main

16 16 Files and Streams Read/Write functions in standard library fgetc Reads one character from a file Takes a FILE pointer as an argument fgetc( stdin ) equivalent to getchar() fputc Writes one character to a file Takes a FILE pointer and a character to write as an argument fputc( 'a', stdout ) equivalent to putchar( 'a' ) fgets Reads a line from a file fputs Writes a line to a file fscanf / fprintf File processing equivalents of scanf and printf

17 Reading from a file using fgets fgets is a better way to read from a file We can read into a string using fgets FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line,1000,fptr) != NULL) { printf ("Read line %s\n",line); } fgets takes 3 arguments, a string, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF)

18 Closing a file We can close a file simply using fclose and the file pointer. Here's a complete "hello files". FILE *fptr; char filename[]= "myfile.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf ("Cannot open file to write!\n"); exit(-1); } fprintf (fptr,"Hello World of filing!\n"); fclose (fptr);

19 Great Muck-Ups in C #72 of 100 We use the file pointer to close the file - not the name of the file FILE *fptr; fptr= fopen ("myfile.dat","r"); /* Read from file */ fclose ("myfile.dat"); /* Ooops - that's wrong */

20 Three special streams Three special file streams are defined in the stdio.h header stdin reads input from the keyboard stdout send output to the screen stderr prints errors to an error device (usually also the screen) What might this do: fprintf (stdout,"Hello World!\n");

21 Using fgets to read from the keyboard fgets and stdin can be combined to get a safe way to get a line of input from the user #include int main() { const int MAXLEN=1000; char readline[MAXLEN]; fgets (readline,MAXLEN,stdin); printf ("You typed %s",readline); return 0; }

22 Example Write a program that contains a function that will be given a text file, count the number of words in this file and return this count.

23 Example Implement a database that manages the information of employees in a company. These data are Name (struct of first name, middle name, last name) Date Of Birth (DOB) (struct of day, month and year) Address (struct of street, city, country) Contacts (struct of telephone number, mobile number, e-mail address)

24 Salary (struct of basic, additional, reductions, taxes) The database program should do the following tasks: (a) Input employee information and check for correctness of fields as necessary.

25 (b) Append new employee data to the database file using a function called Insert_Emp. This function should check if the same name of the employee not exists before updating or otherwise it will message “Already exists” without appending the new information. (c) Modify an existing employee data using a function called Update_Emp. This function should check if the same name of the employee not exists before updating or otherwise it will message “Already exists” without saving the updated information. (d) Delete the information of an employee using a function called Del_Emp. This function should message “are you sure?”

26 (e) Search for an employee with Name or DOB or Telephone number or Mobile number. (f) Be able to sort employees according to Name or DOB or Salary.

27 Binary Files There are up to 100 students, every student has name, up to 10 grades, the actual number of grades is stored, and the gpa : #define STUDENTSN 100 #define MARKSN 10 #define NAMELENN 20 typedef struct { char name[NAMELENN+1]; int marksNumber; double marks[MARKSN]; double gpa; } StudentT; StudentT info[STUDENTSN];

28 saveStudent /* Purpose: write number structures, contained in the * array info, to the file fname. * Returns: 1 if successful; otherwise 0 */ int saveStudent(const char *fname, StudentT info[], int number) { FILE *out; if((out = fopen(fname, "wb")) == NULL) return 0; if(fwrite(info,sizeof(StudentT),number,out)!=number ){ fclose(out); return 0; } if(fclose(out) == EOF) return 0; return 1; }

29 Binary Files Used to store data as binary. fwrite is used to write data to a binary file. fwrite ([&arg], [arg size], [number of arg.], [file pointer]) fread is used to read data from a binary file. fread ([&arg], [arg size], [number of arg.], [file pointer])

30 updateGpa / * Purpose: initialize all of the gpa fields; * reading data from a file and then * writing them back to this file */ int updateGpa(const char *fname) { FILE *inOut; StudentT buffer; int i; if((inOut = fopen(fname, "r+b")) == NULL) return 0; /* read one structure at a time */ while(fread(&buffer,sizeof(StudentT),1,inOut)!= 0) { for(i =0, buffer.gpa = 0.0; i < buffer.marksNumber; i++) /* compute gpa */ buffer.gpa += buffer.marks[i];

31 Example 5 void main(void) { FILE *f1; float x=5.346; char cc[] = “Hello”; f1 = fopen(“c:\\abc.bin”, “wb”); fwrite(&x, sizeof(float), 1, f1); fwrite(cc, sizeof(char), strlen(cc), f1); fclose(f1); }

32 Example 6 void main(void) { FILE *f1; float x; char cc[100]; f1 = fopen(“c:\\abc.bin”, “rb”); fread(&x, sizeof(float), 1, f1); fread(cc, sizeof(char), 5, f1); fclose(f1); }

33 Example 7 void main(void) { FILE *f1, *f2; char c; f1 = fopen(“c:\\abc.bin”, “rb”); f2 = fopen(“c:\\abc_copy.bin”, “wb”); while(!feof(f1)) { fread(&c, sizeof(char), 1, f1); fwrite(&c, sizeof(char), 1, f2); } fclose(f1); fclose(f2); }

34 Example 8 struct Pers_Data { char Name[100]; int ID; char Add[255]; }; void main(void) { Pers_Data P[10]; FILE *f; int i; for( i = 0; i<10; i++) { scanf(“%s”, P[i].Name); scanf(“%d”, &P[i].ID); scanf(“%s”, P[i].Add); } f = fopen(“c:\\DataBase.2”, “wb”); for(i = 0; i<10; i++) fwrite(&P[i], sizeof(Pers_Data), 1, f); }//main

35 Example 9 struct Pers_Data { char Name[100]; int ID; char Add[255]; }; void main(void) { Pers_Data P[10]; FILE *f; int i; for( i = 0; i<10; i++) { scanf(“%s”, P[i].Name); scanf(“%d”, &P[i].ID); scanf(“%s”, P[i].Add); } f = fopen(“c:\\DataBase.3”, “wb”); fwrite(P, sizeof(Pers_Data), 10, f); }//main

36 Example5 Write a 12-hour clock program that declares a clock struct to store hours, minutes, seconds, A.M. and P.M. provide functions to perform the following tasks: Write a 12-hour clock program that declares a clock struct to store hours, minutes, seconds, A.M. and P.M. provide functions to perform the following tasks: Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12- hour clock value of AM or PM Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12- hour clock value of AM or PM

37 Member Access through Pointer If p is a pointer to a structure that has a member w, then p->w gives access to w. Memory Allocation for a Structure For a structure s and a pointer p to this structure, use: if((p = malloc(sizeof(struct s)) == NULL) …

38 Linked Lists A list is a collection of elements; each element contains data; here double values: typedef double DataType; typedef struct elem { DataType value; struct elem *next; } ElemT, *ElemTP; The value of next will be NULL if there is no next element, otherwise it will be a structure representing the next element.

39 Linked Lists: delete (cont.) for(aux = this->first; aux->next->next != NULL; aux = aux->next) ; /* the predecessor of last element */ *value = aux->next->value; free(aux->next); aux->next = NULL; return 1; }

40 Linked Lists: delete int deleteFirst(ListTP this) { ElemTP aux = this->first; if(aux == NULL) /* empty list */ return 0; this->first = aux->next; free(aux); return 1; } void clear(ListTP this) { while(deleteFirst(this)) ; this->first = NULL; }

41 Unions struct intAndDouble { union intOrDouble { int i; int i; double d; double d; }; };

42 Left Shift Left shift: i << j The resulting word will have all bits shifted to the left by j positions; for every bit that is shifted off the left end of the word, there is a zero bit added at the right end. x <<= 1 is equivalent to x *= 2 x <<= 2 is equivalent to x *= 4.

43 Right Shift Right shift: i >> j The resulting word will have all bits shifted to the right by j positions; for every bit that is shifted off the right end of the word, there is a zero bit added at the left end. x >>= 1 is equivalent to x /= 2 x >>= 2 is equivalent to x /= 4.

44 The End


Download ppt "Files Programming 1. 2 What is a File? Is a block of arbitrary information, or resource for storing information, which is available to a computer program."

Similar presentations


Ads by Google