0% found this document useful (0 votes)
4 views

CS112 Programming Languages 1 (Lecture 8 - Spring 2020)

This document is a lecture on file processing in C programming, covering the importance of files for persistent data storage and the use of standard library functions for file input and output. It explains the concepts of files and streams, how to open and manipulate files using pointers, and provides examples of writing to and reading from files. Key practices such as checking for successful file opening and closing files after use are emphasized.

Uploaded by

zeyadzzzzsss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CS112 Programming Languages 1 (Lecture 8 - Spring 2020)

This document is a lecture on file processing in C programming, covering the importance of files for persistent data storage and the use of standard library functions for file input and output. It explains the concepts of files and streams, how to open and manipulate files using pointers, and provides examples of writing to and reading from files. Key practices such as checking for successful file opening and closing files after use are emphasized.

Uploaded by

zeyadzzzzsss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

CS112 – Level 1

Programming Languages 1
( General Division – Software Engineering Program – Medical Informatics Program )

Lecture 8
File Processing [ Input / Output ]

Spring 2020 (Semester 2)


Week 9
Course & Lectures are based on their counterparts in the following courses:
o Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New
South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
2

• C File Processing
• Why Files?
• Files and Streams.
O • Standard Input, Standard Output.
u • Create a Reference to the File (a File
t Pointer).
Outline l • Open the File (using the fopen function).
i
n • Read from the File.
e • Write to the File.
• The Data Hierarchy.

2
The ability to read data from and write data to files is the primary means of
storing persistent (permanent) data, or data which does not disappear when
your program finishes running.
File I/O
We are used to reading from and writing to the terminal:
• read from stdin (Keyboard)
• write to stdout (Monitor)
• write to stderr (Monitor)

But we can also read from


and write to files!
The ability to read data from and write data to files is the primary means of
storing persistent (permanent) data, or data which does not disappear when
your program finishes running.
File I/O
Why Files?

▪ Storage of data in variables and arrays is temporary—such data is lost when


a program terminates.
▪ Files are used for permanent retention of data.
▪ Computers store files on secondary storage devices, especially disk storage
devices.
▪ The C programming language provides many standard library functions for
file input and output. These functions are found in the C standard library
header stdio.h.
o C views each file as a sequence of bytes.
o A file ends with the end-of-file marker.
o A stream is created when a file is opened.
o Provides a communication channel between files and programs

Files and Streams


▪ C views each file simply as a sequential stream of bytes.
▪ In computer science, a stream is a sequence of data elements made available
over time.
▪ Normal functions cannot operate on streams as a whole, as they have
potentially unlimited data
▪ In C, the stream is a common, logical interface to the various devices of the
computer. All input and output is performed with streams, which are
sequences of bytes.
o C views each file as a sequence of bytes.
o A file ends with the end-of-file marker.
o A stream is created when a file is opened.
o Provides a communication channel between files and programs

Files and Streams


▪ A stream is linked to a file using an open operation, and is disassociated from
a file using a close operation.
▪ Each file stream ends with an end-of-file marker (EOF).
▪ Opening a file stream returns a pointer to a FILE structure that contains
information used to process the file.
▪ Three streams are automatically opened when program execution begins—
the standard input, the standard output, and the standard error.
▪ The standard input stream enables a program to read data from the
keyboard, and the standard output stream enables a program to print data
on the screen.
o C views each file as a sequence of bytes.
o A file ends with the end-of-file marker.
o A stream is created when a file is opened.
o Provides a communication channel between files and programs

Files and Streams


The abstraction of files provided by the standard I/O library (stdio) is
implemented in a structure called FILE. Calling fopen returns a pointer to
the file you have just opened. If it returns NULL, then it could not open the
requested file.
Step 1: Create a reference to the file (a file pointer)

FILE* fptr;

Step 2: Open the file (using the fopen function)

FILE *fopen(char *filename, char *mode);


fptr = fopen(“client.txt”, “r”);

1st argument -- path to the file


2nd argument – mode
“r” -- read, “w” -- write, “a” -- append
Almost all of the functions you’ll then use to manipulate your newly opened
file take this file pointer as one of one of their arguments.
The abstraction of files provided by the standard I/O library (stdio) is
implemented in a structure called FILE. Calling fopen returns a pointer to
the file you have just opened. If it returns NULL, then it could not open the
requested file.
Step 1: Create a reference to the file (a file pointer)

FILE* fptr;

Step 2: Open the file (using the fopen function)

FILE *fopen(char *filename, char *mode);


fptr = fopen(“client.txt”, “r”);

1st argument -- path to the file


On success: fPtr is assigned a pointer to the FILE structure
2nd argument – mode
On failure:“r” --fPtr will“w”
read, have--awrite,
NULL value
“a” -- append
Almost all of the functions you’ll then use to manipulate your newly opened
file take this file pointer as one of one of their arguments.
These functions allow us to read from or write to the file we’ve just opened.

Step 3a: Read from the file

▪ fgetc -- returns the next character


▪ fgets -- returns a line of text
▪ fread -- reads a certain # of bytes and places them into an array
▪ fseek -- moves to a certain position

Step 3b: Write to the file

▪ fputc -- writes a character


▪ fputs -- writes a line of text
▪ fprintf -- prints a formatted output to a file
▪ fwrite -- writes an array of bytes to a file
Be sure to fclose any and all files that you have fopened.

Some Operating Systems, such as UNIX, will close any files you’ve left open when
your program terminates, but it is considered poor coding practice to rely on this
behavior.

Step 4: Close the file

fclose(fptr);

Remember!
✓ Always open a file before reading from or writing to it.
✓ Always check the return value to make sure you don't get back a NULL.
✓ Always close a file if you open it.
The Data Hierarchy
o Bit – smallest data item
o Value of 0 or 1
o Byte – 8 bits
o Used to store a character
o Decimal digits, letters, and special symbols
o Field – group of characters conveying meaning
o Example: your name
o Record – group of related fields
o Represented by a struct or a class
o Example: In a payroll system, a record for a particular
employee that contained his/her identification number,
name, address, etc.
o File – group of related records
o Example: payroll file
o Database – group of related files
The Data Hierarchy
Example #1
Writing to a file
#include <stdio.h>
#define STUDENTS 3
int main(void)
{
int scores[] = { 96, 90, 83 };
FILE* file = fopen(“database”, “w”);
if (file != NULL)
{
for (int i = 0; i < STUDENTS; i++)
{
fprintf(file, “%i\n”, scores[i]);
}
fclose(file);
}
}
In this program, we are
storing the values of an
array called scores in a Example #1
file named database.
Writing to a file
#include <stdio.h> We open the file using the fopen function. The
#define STUDENTS 3 second argument "w" tells fopen that we want to
int main(void) write to this file. If a file named database does not
{ already exist, fopen will create it.
int scores[] = { 96, 90, 83 };
FILE* file = fopen(“database”, “w”);
if (file != NULL) if (file != NULL) is
{ a sanity check that the call
for (int i = 0; i < STUDENTS; i++) to fopen didn’t fail.
{
fprintf(file, “%i\n”, scores[i]);
}
fclose(file);
}
fprintf takes a file pointer as its first argument. Instead of printing to
}
the screen, fprintf prints to the file we pass to it.
1 /* Fig. 11.3: fig11_03.c
2 Create a sequential file */
3 #include <stdio.h>
4
5
6
int main()
{ Example #2
7
8
int account; /* account number */
char name[ 30 ]; /* account name */
Writing to a file
9 double balance; /* account balance */
10
11 FILE *cfPtr; /* cfPtr = clients.dat file pointer */
12
13 /* fopen opens file. Exit program if unable to create file */
14 if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL ) {
15 printf( "File could not be opened\n" );
16 } /* end if */
17 else {
18 printf( "Enter the account, name, and balance.\n" );
19 printf( "Enter EOF to end input.\n" );
20 printf( "? " );
21 scanf( "%d%s%lf", &account, name, &balance );
22
23 /* write account, name and balance into file with fprintf */
24 while ( !feof( stdin ) ) {
25 fprintf( cfPtr, "%d %s %.2f\n", account, name, balance );
26 printf( "? " );
27 scanf( "%d%s%lf", &account, name, &balance );
28 } /* end while */ Example #2
29
30 fclose( cfPtr ); /* fclose closes file */ Writing to a file
31 } /* end else */
32
33 return 0; /* indicates successful termination */
34
35 } /* end main */

Program Output:
Enter the account, name, and balance.
Enter EOF to end input.
? 100 Jones 24.98
? 200 Doe 345.67
? 300 White 0.00
? 400 Stone -42.16
? 500 Rich 224.62
? ^Z
1 /* Fig. 11.7: fig11_07.c
2 Reading and printing a sequential file */
3 #include <stdio.h>
4
5 int main()
6
7
{
int account; /* account number */ Example #3
8 char name[ 30 ]; /* account name */
9
10
double balance; /* account balance */ Reading from a file
11 FILE *cfPtr; /* cfPtr = clients.dat file pointer */
12
13 /* fopen opens file; exits program if file cannot be opened */
14 if ( ( cfPtr = fopen( "clients.dat", "r" ) ) == NULL ) {
15 printf( "File could not be opened\n" );
16 } /* end if */
17 else { /* read account, name and balance from file */
18 printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" );
19 fscanf( cfPtr, "%d%s%lf", &account, name, &balance );
20
21 /* while not end of file */
22 while ( !feof( cfPtr ) ) {
23 printf( "%-10d%-13s%7.2f\n", account, name, balance );
24 fscanf( cfPtr, "%d%s%lf", &account, name, &balance );
25 } /* end while */
26
27 fclose( cfPtr ); /* fclose closes the file */
28 } /* end else */
29
30 return 0; /* indicates successful termination */
31
32 } /* end main */
Example #3
Reading from a file

Program Output:
Account Name Balance
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
Thanks! .. Questions?

20

You might also like