![Page 1: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/1.jpg)
TEC 284
C Programming – Part 6File Input and Output
![Page 2: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/2.jpg)
Streams
In C we use pointers to manage streams that read and write data
Streams are just file or hardware devices such as a monitor or pointer which can be controlled by a C program
We use pointers to the stream in order to control them
To point to and manage a file stream in C, an internal data structure called FILE is used
![Page 3: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/3.jpg)
FILE
#include <stdio.h>main () {//create 3 file pointersFILE *pRead;FILE *pWrite;FILE *pAppend;
}
Each FILE pointer can essentially open and manage a separate file
![Page 4: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/4.jpg)
Opening and Closing Files
When working with files, the basic steps involve opening the file, processing the file and then closing the file
After opening the file, there should always be some error checking/handling to ensure the file was successfully opened before working on the file
The fopen() function is used fopen() returns a FILE pointer when
the file is successfully opened
![Page 5: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/5.jpg)
Opening a file in C
main () {FILE *pRead;pRead = fopen(“file1.txt”,“r”);
}
fopen() takes two arguments The name of the file to be opened A flag to indicate how the file should be
opened In this example, the file file1.txt is
opened in read-only mode
![Page 6: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/6.jpg)
Text file open modes
r - read text mode w - write text mode (truncates file to zero
length or creates new file) a - append text mode for writing (opens or
creates file and sets file pointer to the end-of-file)
r+ - read and write text mode w+ - read and write text mode (truncates file
to zero length or creates new file) a+ - read and write text mode (opens or
creates file and sets file pointer to the end-of-file
![Page 7: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/7.jpg)
fopen() results
If the file does not exist and it is opened with read mode (r), then the open fails.
If the file is opened with append mode (a), then all write operations occur at the end of the file regardless of the current file position.
On success a pointer to the file stream is returned. On failure a null pointer is returned
![Page 8: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/8.jpg)
Opening a file in C with error handling
main () {FILE *pRead;pRead = fopen(“file1.txt”,“r”);if(pRead == NULL) {
printf(“\nFile could not be opened”);} else {
printf(“\nFile was opened for reading”);}
}
![Page 9: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/9.jpg)
Check for NULL
if(pRead == NULL)Can be shortened to if(pRead)
If pRead returns a non-NULL, the if condition is true.
If pRead returns NULL, the condition is false
![Page 10: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/10.jpg)
Closing a file
After opening and processing a file, the file should be closed using fclose()
fclose() uses the FILE pointer to flush the stream and close the file
This frees up memory resources for the CPU and is good programming practice
fclose() takes a pointer to a file as its argument fclose(pRead);
![Page 11: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/11.jpg)
Reading a file
For simplicity, the test file the example is referring to is just a text file containing names
Names.txtJohnMichaelFrankStacyRobert
![Page 12: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/12.jpg)
Reading a file
main () {FILE *pRead;
char name[20];pRead = fopen(“Names.txt”,“r”);if(pRead == NULL) {
printf(“\nFile could not be opened”);} else {
printf(“\nContents of file:\n”);fscanf(pRead, “%s”, name);while(!feof(pRead)) {//feof() checks for end-of-file//feof() returns a non-zero value when the end-of-file//marker is reached
printf(“%s\n”,name);fscanf(pRead, “%s”, name);
}fclose(pRead);
}}
![Page 13: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/13.jpg)
Results of the program
Contents of file :JohnMichaelFrankStacyRobert
![Page 14: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/14.jpg)
Reading multiple fields
fscanf() can read multiple fields by supplying a series of type specifiers for the second argument
E.g. fscanf(pRead, “%s%s”, name, hobby);
The %s specifier will read a series of characters until a white space is found, including a blank, new line or tab
![Page 15: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/15.jpg)
Other types of specifiers for file reads
Type Description
c Single character
d Decimal integer
e, E, f, g, G Floating point
o Octal integer
s String of characters
u Unsigned decimal integer
x, X Hexadecimal integer
![Page 16: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/16.jpg)
Reading multiple fields test file Hobbies.txt
Michael ProgrammingSheila ShoppingSpencer FootballOlivia Dancing
![Page 17: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/17.jpg)
Code to read multiple fieldsmain () {
FILE *pRead;char name[20], char hobby[15];
pRead = fopen(“Hobbies.txt”,“r”);if(pRead == NULL) {
printf(“\nFile could not be opened”);} else {
printf(“\nName\tHobby\n\n”);fscanf(pRead, “%s%s”, name, hobby);while(!feof(pRead)) {//feof() checks for end-of-file//feof() returns a non-zero value when the end-of-file//marker is reached
printf(“%s\t%s\n”,name, hobby);fscanf(pRead, “%s%s”, name, hobby);
}fclose(pRead);
}}
![Page 18: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/18.jpg)
Results
Name Hobby
Michael ProgrammingSheila ShoppingSpencer FootballOlivia Dancing
![Page 19: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/19.jpg)
Writing Data
Similarly to how printf() is used to send information to the screen fprintf() can be used to send information to a file
fprintf() uses a FILE pointer to write data to a file
The fprintf() function takes a FILE pointer, a list of data types and a list of values (or variables) to write the information to a file
![Page 20: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/20.jpg)
Writing to a file
main () {FILE *pWrite;
char fName[20], char lName[20], char id[15], float gpa;pWrite = fopen(“Students.txt”,“w”);if(pRead == NULL) {
printf(“\nFile could not be opened”);} else {
printf(“\nEnter first name, last name, id and GPA\n”);printf(“Enter data separated by spaces: ”);//store data entered by the user into variablesscanf( “%s%s%s%f”, fName, lName,id, &gpa );//write variable contents separated by tabsfprintf(pWrite, “%s\t%s\t%s\t%.2f\n”,fName, lName, id,
gpa);
fclose(pWrite);} //end if
}
![Page 21: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/21.jpg)
Reading the same record backmain () {
FILE *pRead;char fName[20], char lName[20], char id[15], float gpa;
pRead = fopen(“Students.txt”,“r”);if(pRead == NULL) {
printf(“\nFile could not be opened”);} else { //print heading
printf(“\nName\t\tID\t GPA\n\n”);//read field info from file and store in variablesfscanf( “pRead”, “%s%s%s%f”, fName, lName,id, &gpa );//print variable data to standard outputprintf(“%s %s\t%s\t%.2f\n”,fName, lName, id, gpa);
fclose(pRead);} //end if
}
![Page 22: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/22.jpg)
Appending to a file
When opening a file using fopen() with a w argument value will erase any previous data stored in the file
Use the a attribute to append data at the end of the file
If the file does not exist, a new one will be created
![Page 23: C Programming – Part 6 File Input and Output. In C we use pointers to manage streams that read and write data Streams are just file or hardware devices](https://reader036.vdocuments.mx/reader036/viewer/2022081506/56649eff5503460f94c14c86/html5/thumbnails/23.jpg)
Appending code example//This program appends to our previous Hobbies.txt file examplemain () {
FILE *pWrite;char name[20], char hobby[20];
pWrite = fopen(“Hobbies.txt”,“a”);if(pRead == NULL) {
printf(“\nFile could not be opened”);} else {
printf(“\nEnter a new name and hobby: ”);//store data entered by the user into variablesscanf( “%s%s”, name, hobby);//write variable contents separated by tabsfprintf(pWrite, “%s\t%s\n”,name, hobby);
fclose(pWrite);} //end if
}