CS352 – OOP & Data Structures
Dr. V. Vijaya Saradhi,
Dept. Of CSE,
IIT Guwahati
saradhi@iitg.ac.in
File I/O
(Excluding file streams)
Overview
● Introduction
● Reading methods – Open, Read, Write, Close
● Reading integers which are in one line
● Reading integers which are in different lines
● Reading using loop
● Reading matrix of integers
● Reading characters in one line
3
Overview
● Reading characters from several lines
● Reading strings in one line
● Reading several strings in one line
● Reading several strings in multiple lines
● Reading integers separated by comma
● Reading strings separated by comma
4
Overview
● Parsing
5
Introduction
Introduction - 01
● Standard I/O typically uses line-based input, requiring the user to type and press Enter,
whereas file input reads data from disk buffers, enabling automated and faster
processing.
● Line input from standard I/O is interactive and slow, while file I/O uses buffered input
which reads large chunks of data at once, improving efficiency for large datasets.
● Reading from files minimizes human error in data entry and ensures consistency,
unlike manual input where typos and formatting issues are common.
● File input supports parsing structured data formats (like CSV or JSON) more effectively
than line-by-line user input.
7
Introduction - 02
● Buffered file input allows programs to read binary data and non-printable characters,
which is not feasible with standard text input.
● Standard input is transient and reset with each run, but file input enables programs to
read historical or previously stored data across sessions.
● File reading is essential for processing real-world data sources such as log files,
sensor outputs, and configuration files that cannot be entered interactively.
● Buffering in file I/O improves performance by reducing the number of read operations
compared to the character-by-character or line-by-line approach of standard input.
8
Introduction - 03
● File streams can be repositioned using seek operations, allowing random access to
specific parts of the data, unlike linear standard input.
● Learning file input teaches students to handle edge cases like EOF (End of File), file not
found, or read errors, which are critical for robust programming.
9
Reading Methods
Reading Methods - 01
● For opening a file, reading a file, writing into a file or closing a file, FILE * input
structure is used
● To read a file you must perform the following three tasks:
● Open a file and obtain file pointer
● Perform reading and/or writing
● Close the file pointer
11
Opening File For Reading
Opening File For Reading - 01
● To open a file for reading or writing, use fopen function
● fopen is a standard library function in C used to open a file for reading, writing, or appending.
● It is defined in the standard header and returns a pointer to a FILE structure.
● If the file is opened successfully, fopen returns a valid FILE * that can be used for file
operations.
● If the file cannot be opened due to issues like missing file or permission denial, fopen returns
NULL.
● It is the primary way to begin file handling in C, used before performing read/write/close
operations.
13
Opening File For Reading - 02
● Input parameters for fopen function are
● Name of the file to read
● Mode in which the file should be opened
● The first parameter is a string that gives the file’s name or path, such as "data.txt" or
"./folder/file.txt"
● The second parameter is a mode string like "r", "w", "a", "r+", etc., indicating read,
write, or append access.
14
Opening File For Reading - 03
● The mode string controls whether the file is opened for input, output, or both, and
whether it will be created or overwritten.
● The file path and mode together determine the accessibility and behavior of the file
when opened.
fopen("cs352.txt", "r"); //Open file named cs352.txt in reading mode only
fopen("cs352.txt", "w"); //Open file named cs352.txt in writing mode only
fopen("cs352.txt", "r+"); //Open file named cs352.txt in read and write mode
fopen("cs352.txt", "w+"); //Open file named cs352.txt in read and write mode
15
Opening File For Reading - 04
● "r+" opens an existing file for both reading and writing.
● The file must already exist; if it does not, fopen("filename", "r+") will return NULL.
● The file pointer is positioned at the beginning of the file.
● You can read from and write to the file without closing and reopening it in a different
mode.
● However, writing does not automatically erase the content unless you overwrite it
explicitly.
16
Opening File For Reading - 05
● "w+" opens a file for both reading and writing, but it also creates a new file if it doesn’t
exist.
● If the file already exists, all its contents are erased (truncated) as soon as it's opened.
● The file pointer is positioned at the beginning of the file.
● This mode is useful when you want to rewrite a file and also read from it during the
same session.
● Be cautious: using "w+" will delete existing file contents, even if you only intend to
read.
17
fscanf - Reading From FILE *
fscanf - Reading From FILE * - 01
● fscanf() is used to read formatted data from a file, similar to how scanf() reads from
standard input.
● It takes a FILE * handle as its first argument, followed by a format string and variable
addresses to store the read values.
● The format string specifies the expected types in the file, such as %d for integers, %f for
floats, and %s for strings.
● Each call to fscanf() reads data starting from the current file position and moves forward as
data is read.
● You should always check the return value of fscanf() to ensure that the expected number of
items were successfully read.
19
Reading From FILE * - 02
● Reading from a file can be done using functions like fgetc(), fgets().
● These functions use the FILE * to read characters, strings, or formatted data from the
file.
● The file must be opened in read mode ("r") or read/write mode ("r+").
● Reading continues until data ends or an error occurs, usually detected by comparing
with EOF.
● Reading allows the program to process and analyze data stored externally.
20
fprintf – Writing To File Using FILE *
fprintf - Writing To File Using FILE * - 01
● fprintf() is used to write formatted data to a file, similar to how printf() writes to the
screen.
● The first argument to fprintf() is a FILE * handle that specifies the file where the output
should be written.
● The second argument is a format string that defines how the data should be printed, followed
by the actual values.
● The data is written starting from the current file position, and fprintf() automatically moves
the position forward after writing.
● fprintf() returns the number of characters written, or a negative value if an error occurs, so
checking the return value can help detect write failures.
22
Writing To File Using FILE * - 02
● Writing to a file is done using functions like fputs(), or fputc().
● The file must be opened in a mode that allows writing, such as "w" or "a".
● Mode "w" overwrites existing content, while "a" appends data at the end.
● Writing sends output from the program into the file instead of the screen.
● Always check that the file is opened successfully before writing to avoid data loss.
23
fclose – Closing FILE *
fclose – Closing FILE * - 01
● fclose(FILE *fp) is a standard C function that closes an open file associated with the given
file pointer.
● When you call fclose(), it flushes any data remaining in the output buffer to the file and
releases system resources used by the file.
● Failing to call fclose() can result in incomplete writes, especially if data was buffered but
not yet saved to disk.
● If too many files are opened without closing them, the program may exceed the system's
limit on open file descriptors, leading to errors.
● Using a file pointer after calling fclose() leads to undefined behavior, and such pointers
should not be reused unless reassigned via fopen()
25
fclose – Closing FILE * - 02
● When you write to a file using fprintf() or fputs(), the data is not always written
immediately to disk.
● Instead, it is stored temporarily in a buffer (an area in memory) to improve performance.
● This buffering allows the system to write large chunks at once rather than performing
frequent small writes.
● When fclose() is called, it forces (flushes) all the remaining data in the buffer to be written
to the file.
● If fclose() or fflush() is not called, some or all of the buffered data may be lost if the
program crashes or exits unexpectedly.
26
Examples
Example - 01
28
Example - 02
29
Example - 03
30
Example - 04
31
Example - 05
32
Example - 06
33
File Permissions & File Opening Mode
File Permissions and File Open Mode - 01
● In most operating systems, each file has permission flags for reading (r), writing (w),
and executing (x).
● These permissions determine what actions users or programs are allowed to perform
on the file.
● Permissions are set separately for the file's owner, group, and others (public users).
● For example, a permission like rw-r--r-- means the owner can read and write, while
others can only read.
● These permissions are crucial in managing file security and controlling access.
35
File Permissions and File Open Mode - 02
● If a file does not have read permission, trying to open it with "r" or "r+" using fopen will fail.
● If a file lacks write permission, opening it with "w", "w+", or "a" will fail unless the file is
created anew.
● Execute permission does not impact fopen, as it is relevant only when trying to run the file as
a program.
● fopen relies on the operating system to enforce permission checks before granting access to
the file.
● Incorrect permissions will result in fopen returning NULL, and the program must check this
to avoid undefined behavior.
36
File Permissions and File Open Mode - 03
● There is a clear relationship between file opening modes (like "r", "w", "a") and the file
permissions set by the operating system.
● The file opening mode in fopen() determines what kind of access the program is
requesting—whether it wants to read, write, or append data.
● The file's permissions control whether the operating system will allow the requested
access based on who the user is (owner, group, or others).
37
File Permissions and File Open Mode - 04
● For example, opening a file in "r" mode requires the file to exist and have read
permission for the user running the program.
● Similarly, opening a file in "w" or "a" mode requires the file to have write permission,
or the program will not be allowed to modify or create the file.
● Thus, even if a program specifies a mode in fopen, actual access depends on whether
the file system grants the required permission to perform that operation.
38
What is FILE *?
What is FILE * ? - 01
● FILE * is a pointer to a structure that holds information about a file
● This structure is defined in the <stdio.h> header and is used for all file operations.
● When a file is opened using fopen(), it returns a FILE * which is used to access the
file.
● The pointer stores the file’s current position, access mode, buffer status, and error
indicators.
● You must always check if FILE * is NULL to confirm that the file was opened
successfully.
40
What is FILE * ? - 02
● It holds a FILE related structure whose members are
● File Descriptor – A low-level integer that uniquely identifies the file for the OS.
● File Position Indicator – Tracks the current read/write position in the file.
● Buffer – A memory area for storing chunks of data to improve performance.
● Flags – Status indicators like end-of-file (EOF) or error states.
● Mode – Information about whether the file is opened for reading, writing, or both.
41
What is FILE * ? - 03
Struct FILE
File name
Mode
Buffer
File position
Status
42
Why FILE * ?
Why FILE * ? - 01
● FILE * is a pointer to a FILE structure defined
● This structure contains all the information needed to manage a file: its current
position, buffer, and status flags.
● Instead of directly dealing with low-level file descriptors, FILE * provides a higher-
level abstraction for easier file handling.
● The * indicates that the variable is a pointer type, meaning it points to this structure in
memory.
● Using FILE * allows the same set of functions (fopen, fread, fprintf, etc.) to work
with different files by simply passing the pointer.
44
What FILE * returns?
What FILE * returns?
● When you call fopen(), it allocates a FILE structure and returns its address, i.e., a FILE
*.
● If the file is opened successfully, the FILE * points to the structure containing all
necessary details about that file.
● If the file cannot be opened (e.g., missing file or permission error), fopen() returns
NULL.
● This return value is used to check whether file operations can proceed.
● Thus, FILE * acts as a file “handle” through which all subsequent operations are
performed.
46
Reading Integers Which Are In One Line
Reading Integers Which Are In One Line
48
Reading Integers Which Are In Different Lines
Reading Integers Which Are In Different Lines
50
Reading Integers Using Loops
Reading Integers Using Loops
52
Reading Integers Using Loops
53
Reading Integers Using Loops
54
Reading Integers Using Loops
55
Use of EOF
Use of EOF
57
Reading Integers Using Loops
58
Reading Matrix Of Integers
Reading Matrix of Integers
60
Reading Matrix Of Integers
61
Reading Characters In One Line
Reading Characters In One Line - 01
63
Reading Characters In One Line - 02
Why j value is NOT b?
Why k value is NOT c?
fscanf("%c%c%c", &I, &j, &k);
Scanning three continuous characters that is "aSPACEb 64
Reading Characters In One Line - 03
65
Reading Characters In One Line - 04
Why this is working?
fscanf("%c %c %c", &I, &j, &k);
Scanning FORMAT changed to "%cSPACE%cSPACE%c"
66
Reading Characters In One Line - 05
67
Reading Characters In One Line - 06
Why is this working?
fscanf("%c%c%c%c%c", &I, &temp, &j, &temp, &k);
68
Reading Characters From Multiple Lines
Reading Characters From Multiple Lines - 01
70
Reading Characters From Multiple Lines - 02
Why is this NOT working?
INPUT File contains NEWLINES at the end of every character.
One new character present in first line is read into variable j
71
Reading Characters From Multiple Lines - 03
72
Reading Characters From Multiple Lines - 04
73
Reading Characters From Multiple Lines - 05
Why is this working?
Scanning format has "%c\n"
Scans a value & a NEWLINE character
74
Reading Characters From Multiple Lines - 06
Why is this working?
Scanning format has "%c\n"
Scans a value & a NEWLINE character
75
Use of EOF
Use of EOF
77
Reading Integers Using Loops
78
Reading Strings From One Line
Reading Strings From One Line - 01
80
Reading Strings From Multiple Lines - 02
81
Reading Strings From Multiple Lines
Reading Strings From Multiple Lines - 01
83
Reading Strings From Multiple Lines - 02
84
Reading Integers Separated By Comma
Reading Integers Separated By Comma - 01
86
Reading Integers Separated By Comma - 02
87
Reading String Separated By Comma
Reading String Separated By Comma - 02
● We cannot with simple read files whose data
is stored as shown.
● Files often contain more than one data value in a
line, and parsing helps to extract each correctly.
● Different file formats require different parsing
strategies, like reading word-by-word or
number-by-number.
● Parsing handles both simple files like CSV and
complex files with structured data.
89
Reading String Separated By Comma - 02
● Proper parsing ensures data accuracy, reduces errors, and avoids wrong
computations.
● Parsing is a common task in programming problems like file processing, data
cleaning, and log analysis.
● Parsing helps in converting raw input from files into meaningful variables that a program can use.
● Without parsing, a program cannot understand how to interpret the sequence of characters read
from a file.
● Files often contain more than one data value in a line, and parsing helps to extract each correctly.
● Different file formats require different parsing strategies, like reading word-by-word or number-by-
number.
90
Reading String Separated By Comma - 03
● Parsing handles both simple files like CSV and complex files with structured data.
● Proper parsing ensures data accuracy, reduces errors, and avoids wrong
computations.
● Parsing is a common task in programming problems like file processing, data
cleaning, and log analysis.
91
Reading String Separated By Comma - 04
● strtok() is used to split a string into tokens using a delimiter like comma or space.
● It is useful when the number of values in a line is not fixed.
● Each call to strtok(NULL, delimiter) returns the next token.
● You must use fgets() first to read the line before tokenizing.
● Be cautious: strtok() modifies the original string.
92
Reading String Separated By Comma - 05
93
Use of EOF