Introduction To Programming (C/C++) : Chapter 9: File Handling
Introduction To Programming (C/C++) : Chapter 9: File Handling
Programming (C/C++)
• Data files
− Can be created, updated, and processed by C
programs
− Are used for permanent storage of large
amounts of data
• Storage of data in variables and arrays is only
temporary
Bit 1 Or 0
• Creating a File
− FILE *myPtr;
• Creates a FILE pointer called myPtr
− myPtr = fopen("myFile.dat",
openmode);
• Function fopen returns a FILE pointer
to file specified
• Takes two arguments – file to open and
file open mode
• If open fails, NULL returned
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 9
Creating a Sequential Access File
(continued)
− feof( FILE pointer )
• Returns true if end-of-file indicator (no
more data to process) is set for the
specified file
− fclose( FILE pointer )/fcloseall()
• Closes specified file
• Performed automatically when program
ends
• Good practice to close files explicitly
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 10
Creating a Sequential Access File
(continued)
Mode Description
r Open a file for reading.
Create a file for writing. If the file already
w
exists, discard the current contents.
Append; open or create a file for writing at end
a
of file.
r+ Open a file for update (reading and writing).
Create a file for update. If the file already
w+
exists, discard the current contents.
Append; open or create a file for update;
a+
writing is done at the end of the file.
Table of file open modes
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 11
Reading Data from a Sequential
Access File
• Reading a sequential access file
− Create a FILE pointer, link it to the file to
read
myPtr = fopen( "myFile.dat", "r" );
− Use fscanf to read from the file
• Like scanf, except first argument is a
FILE pointer
fscanf(myPtr, "%d%s%f", &myInt,
&myString, &myFloat);
− Data read from beginning to end
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 12
Reading Data from a Sequential
Access File (continued)
• More convenient methods of reading a
string with fscanf
− %[characters]: read until all characters are not
found
− %[^characters]: read until any characters is
found.
• Example:
<ID>-<Name>(<Gender>)tab<Birthday>tab<Grade>
09121234-N. T. Dep(Female) 19/09/99 8.5
• ch10-File01.cpp
• ch10-File02.cpp
• ch10-File03.cpp
}byte offsets
}
}
}
}
}
}
100 100 100 100 100 100
bytes bytes bytes bytes bytes bytes
}
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 32
Assignment
Write a program that uses functions to perform
the following operations:
• Read 3 integers from the keyboard and write
that numbers to a file
• Read 3 integers from the “input.txt” file, solve
quadratic equation (ax2+ bx + c = 0) and write
the results to the “output.txt” file