Introduction to Problem Solving and Programming Lecture 11 (Files) PDF

Summary

This document is a lecture on files in C programming. The lecture provides an overview of file types (text and binary) and the steps for using files. It gives examples on how to declare file pointers and use functions such as fopen, fprintf, fscanf, fwrite, and fread for file operations.

Full Transcript

Lecture 11 – Files  So far, all our examples obtained their input from the keyboard and displayed their output on the Screen.  However, in many real-life applications, the input data is so much that it will be inconvenient to expect the user to type it each time the progra...

Lecture 11 – Files  So far, all our examples obtained their input from the keyboard and displayed their output on the Screen.  However, in many real-life applications, the input data is so much that it will be inconvenient to expect the user to type it each time the program is run. ◦ For example: A program to generate employee pay slip from employee data.  Similarly, there are many applications where the output will be more useful if it is stored in a file rather than the screen. ◦ For example: In the program that generates pay slip, how can we print the pay slips and distribute them to the employees if the output is printed on the screen? Text files Used to store data as binary. Used to store data as text. Binary files 1.Declare variables of type FILE to represent the files 2.Open the files for reading / writing / appending. 3.Read/write from/to the files. 4.Close the files after processing the data. 4 You can declare the file pointer (binary of text) as the following: FILE *f1;  f1 is a pointer Text Files Binary Files Read f1 = fopen("data.txt", f1 = fopen("data.t", "rb"); "r"); Write f1 = fopen("data.txt", f1 = fopen("data.t", “w"); “wb"); appen f1 = fopen("data.txt", f1 = fopen("data.t", d “a"); “ab"); Text Files Binary Files Read fscanf fread Write fprintf fwrite void main(void) { FILE *f1; float x=5.346; char A[] = “Hello”; f1 = fopen(“c:\\abc.txt”, “wt”); fprintf( f1, “%s %f”, A, x); fclose(f1); } void main(void) { FILE *f1; float x; char A; f1 = fopen(“c:\\abc.txt”, “rt”); fscanf( f1, “%s %f”, A, &x); fclose(f1); } 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); } struct Pers_Data { char Name; f = fopen(“c:\\DataBase.1”, “wt”); int ID; char Add; for( i = 0; i

Use Quizgecko on...
Browser
Browser