Professional Documents
Culture Documents
FILE INPUT
AND OUTPUT
CUIT101/111/114 CUT-SEST 3/24/2017
2 CONTENTS
• What is a file?
• Types of Files
• File Handling Functions
• Example Code
CUIT101/111/114 CUT-SEST 3/24/2017
3 WHAT IS A FILE?
4 TYPES OF FILES
• ASCII TEXT(.txt)
• Stores sequences of characters
• Read/write one character at a time (no simultaneous operations)
• Functions actually process data sequentially (even full-line reading functions)
• Character conversions may be done to suit operating system requirements.
• Processed sequentially from beginning to end-of-file (EOF)
• BINARY
• Stores collections of bytes
• No sequential processing of data
• Each byte transferred to/from disk unprocessed
• Allow both sequential access and random-access
• Processed using simultaneous read and write operations
• E.g. Database files
CUIT101/111/114 CUT-SEST 3/24/2017
8 OPENING A FILE
Option Meaning
r Opens a text file in read mode
w Opens or creates a text file in write mode
a Opens a file in append mode
r+ Opens a text file in both read and write mode
w+ Opens a text file in both read and write mode
a+ Opens a text file in both read and write mode
CUIT101/111/114 CUT-SEST 3/24/2017
Option Meaning
rb Opens a binary file in read mode
wb Opens a binary file in write mode
ab Opens a binary file in append mode
rb+ Opens a binary file in both read and write mode
wb+ Opens a binary file in both read and write mode
ab+ Opens a binary file in both read and write mode
CUIT101/111/114 CUT-SEST 3/24/2017
if (file_ptr == NULL)
{
printf("File %s does not exist! \n", MYFILE);
}
CUIT101/111/114 CUT-SEST 3/24/2017
14 OVERWRITING A FILE
{ fclose(file_ptr);
CUIT101/111/114 CUT-SEST 3/24/2017
• fgets() reads full line, provided you know the length of each line
in the file. If you don’t, use Options 2 or 3.
CUIT101/111/114 CUT-SEST 3/24/2017
char c;
do
c = fgetc(file_ptr);
while (c != '\n')
• Read character by character until you get to the end of line marker
CUIT101/111/114 CUT-SEST 3/24/2017
• //0x means what follows is HEX number HENCE 0x1000 = 16 3+ 0*162 + 0*161 +
0*160 = 4096
CUIT101/111/114 CUT-SEST 3/24/2017
printf("%s", buf);
do { fclose(file_ptr);
CUIT101/111/114 CUT-SEST 3/24/2017