Basics
A file has to be opened before a data can be read from or written to it.
Dat is read from a file and then manipulated by program logic.
The output is often written to another file because different functions can read the same file, a common buffer and file position indicator are maintained in memory for function to know how much of the file has already been read.
C supports End of File (EOF) and file related issues
Opening and Closing files
File pointers and Buffers
File read/write function
File Error Handling
Text and Binary File
Reading and Writing binary file
Manipulating file position
Other file handling function
2. Agenda
• Basics
• Opening and Closing files
• File pointers and Buffers
• File read/write function
• File Error Handling
• Text and Binary File
• Reading and Writing binary file
• Manipulating file position
• Other file handling function
2
P.Ananthi, Asssistant Professor, Kongu Engineering College
3. File
FILE IS A NAMED CONTAINER OF
INFORMATION THAT IS STORED
IN MULTIPLE BLOCKS IN A FILE
SYSTEM.
THIS SYSTEM TYPICALLY RESIDES
IN THE HARD DISK BUT A CD-
ROM, DVD-ROM OR FLASH DRIVE
FILES ARE OPERATED BY THE
OPERATING SYSTEM WHICH
ALLOCATES AND DEALLOCATES
DISK BLOCKS
THE OS ALSO CONTROLS THE
TRANSFER OF DATA
BETWEEN PROGRAMS AND THE
FILES THEY ACCESS.
3
P.Ananthi, Asssistant Professor, Kongu Engineering College
4. File Handling basics
• A file has to be opened before a data can be read from or written to it.
• Dat is read from a file and then manipulated by program logic.
• The output is often written to another file because different functions can read the same file, a common
buffer and file position indicator are maintained in memory for function to know how much of the file has
already been read.
• C supports End of File (EOF) and file related issues
• Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high reusability.
• Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed coding is minimized with
this feature.
• Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part of a file using few
instructions which saves a lot of time and reduces the chance of errors.
• Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything simultaneously in a program.
4
P.Ananthi, Asssistant Professor, Kongu Engineering College
6. Text File
• A text file contains data in the form of ASCII characters and is
generally used to store a stream of characters.
• Each line in a text file ends with a new line character (‘n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
• A text file is a human-readable file that contains plain text,
usually encoded in ASCII or Unicode.
• In a text file, data is represented as a sequence of characters,
including letters, digits, and special symbols, with each
character encoded using a specific character encoding
standard (e.g., ASCII, UTF-8).
• Text files are commonly used for storing textual information
such as source code, configuration files, and simple data sets.
• Text files are easy to read and edit using a text editor.
6
P.Ananthi, Asssistant Professor, Kongu Engineering College
7. Binary File
• A binary file contains data in binary form (i.e. 0’s and
1’s) instead of ASCII characters. They contain data that is
stored in a similar manner to how it is stored in the main
memory.
• The binary files can be created only from within a program
and their contents can only be read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
• A binary file contains data in a format that is not human-
readable. It can store a wide range of data types, including
images, audio, video, compiled programs, and complex data
structures.
• Binary files are not constrained by character encodings, and
they can represent data in its raw, binary form.
• Reading and interpreting the contents of a binary file often
requires specific knowledge of the file format and data
structure.
• Binary files can be more efficient for storing and processing
certain types of data, especially non-textual data.
7
P.Ananthi, Asssistant Professor, Kongu Engineering College
8. File operations
• Creating a new file – fopen() with attributes as “a”
or “a+” or “w” or “w+”
• Opening an existing file – fopen()
• Reading from file – fscanf() or fgets()
• Writing to a file – fprintf() or fputs()
• Moving to a specific location in a file – fseek(),
rewind()
• Closing a file – fclose()
8
P.Ananthi, Asssistant Professor, Kongu Engineering College
9. File pointer
• A file pointer is a variable that holds the memory
address of a file stream. It is used to navigate
through a file during input and output operations.
• The FILE data type in C represents a file stream,
and a file pointer is a variable of this type.
• Common file operations involve opening a file,
moving the file pointer to a specific position,
reading or writing data, and closing the file.
• Examples of file pointer-related functions include
fopen(), fclose(), fseek(), ftell(),
fread(), and fwrite().
FILE *filePointer;
filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
printf("File could not be opened.");
return 1;
}
// Perform operations using filePointer
fclose(filePointer);
9
P.Ananthi, Asssistant Professor, Kongu Engineering College
10. File Buffer
• A file buffer, or simply a buffer, is an area in memory used to
temporarily store data read from or written to a file.
• Buffers are employed to improve the efficiency of file operations by
reducing the number of direct read or write operations to the file,
which can be slower.
• Standard C library functions such as fread() and fwrite() often
use a buffer to transfer data between the file and memory.
• Buffers can be implemented as arrays, and their size can be adjusted
based on the amount of data you want to read or write at once.
FILE *filePointer;
char buffer[1024]; // Buffer size of 1024 bytes
filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
printf("File could not be opened.");
return 1;}
// Read data into the buffer
while (fgets(buffer, sizeof(buffer), filePointer) !=
NULL) {
// Process or print the data in the buffer
printf("%s", buffer);
}
fclose(filePointer);
10
P.Ananthi, Asssistant Professor, Kongu Engineering College
11. File pointer and Buffer
• A file pointer is a reference to a particular position in the opened file. It is used in file
handling to perform all file operations such as read, write, close, etc. We use
the FILE macro to declare the file pointer
• Syntax of File Pointer
FILE* pointer_name;
• File Pointer is used in almost all the file operations in C.
• The FILE macro is defined inside <stdio.h> header file.
11
P.Ananthi, Asssistant Professor, Kongu Engineering College
12. File pointer and Buffer
• File handling has two important consequences- creation of file pointer and file
buffer.
• The file pointer is a variable that points to a structure typdef'd to FILE.
• The file position indicator, also called file offset pointer, has an important role in
input/output operations.
• All read/ write operations on files actually take place through buffer. It is connected
to a disk file by the file pointer which is generated when a file opened with fopen.
• The following information is associated when a file is opened,
o The mode of opening
o The location of file buffer
o The file position indicator
o Whether EOF or any errors have been encountered on reading or writing.
12
P.Ananthi, Asssistant Professor, Kongu Engineering College
13. Opening a File
• For opening a file in C, the fopen() function is used
with the filename or file path along with the
required access modes.
FILE* fopen(pathname,access_mode);
• Parameters
• Path name: name of the file when present in the
same directory as the source file/ full path.
• access_mode: Specifies for what operation the file
is being opened.
• Return Value
• If the file is opened successfully, returns a file
pointer to it.
• If the file is not opened, then returns NULL.
13
P.Ananthi, Asssistant Professor, Kongu Engineering College
14. Fiel modes in C
Mode File opened for Return
r Reading only. Error if file doesn't exist
r+ Both reading and writing Error if file doesn't exist
w Writing only If file exist it is overwritten, else create a new file
w+ Both reading and writing If file exist it is overwritten, else create a new file
a Append only Create file if doesn't exist
a+ Reading entire file but only appending permitted Create file if doesn't exist
b Same on their non-prefixed counter parts, expect the binary mode is used
14
P.Ananthi, Asssistant Professor, Kongu Engineering College
15. Fiel modes
for Text
files
Mode Description Example
"r"
Opens the file for reading. Must
exist.
FILE *filePointer =
fopen("example.txt", "r");
"w"
Opens the file for writing.
Truncates if it exists.
FILE *filePointer =
fopen("example.txt", "w");
"a"
Opens the file for writing at the
end.
FILE *filePointer =
fopen("example.txt", "a");
"r+"
Opens the file for reading and
writing.
FILE *filePointer =
fopen("example.txt", "r+");
"w+"
Opens the file for writing and
reading (truncates).
FILE *filePointer =
fopen("example.txt", "w+");
"a+"
Opens the file for reading and
writing at the end.
FILE *filePointer =
fopen("example.txt", "a+");
15
P.Ananthi, Asssistant Professor, Kongu Engineering College
16. Fiel modes for binary files
Mode Description Example
"rb" Opens the file for reading in binary mode. FILE *filePointer = fopen("example.bin", "rb");
"wb" Opens the file for writing in binary mode. Truncates. FILE *filePointer = fopen("example.bin", "wb");
"ab" Opens the file for writing in binary mode at the end. FILE *filePointer = fopen("example.bin", "ab");
"r+b" Opens the file for reading and writing in binary mode. FILE *filePointer = fopen("example.bin", "r+b");
"w+b" Opens the file for writing and reading in binary mode (truncates). FILE *filePointer = fopen("example.bin", "w+b");
"a+b" Opens the file for reading and writing in binary mode at the end. FILE *filePointer = fopen("example.bin", "a+b");
16
P.Ananthi, Asssistant Professor, Kongu Engineering College
17. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fptr;
fptr = fopen("filename.txt", "r");
if (fptr == NULL) {
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}
return 0;
}
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w");
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
}
17
P.Ananthi, Asssistant Professor, Kongu Engineering College
18. File Close
• The fclose() function is used to close an open
file stream.
• It is essential to close files properly to release
system resources associated with the file and
ensure that data is properly flushed and written to
the file before the program terminates.
#include <stdio.h>
int main() {
FILE *filePointer = fopen("example.txt", "w");
if (filePointer == NULL) {
printf("Error opening file for writing.n");
return 1;
}
fprintf(filePointer, "Hello, File!n");
if (fclose(filePointer) == 0) {
printf("File closed successfully.n");
} else {
printf("Error closing file.n");
}
return 0;
}
18
P.Ananthi, Asssistant Professor, Kongu Engineering College
19. File Read/Write Function
• The standard library offers a number of
functions for performing read/ write
operations on files.
Functions Read Write
Character oriented
functions
fgetc fputc
Line-oriented
functions
fgets fputs
Formatted functions fscanf fprintf
Array and Structure
oriented functions
fread fwrite
19
P.Ananthi, Asssistant Professor, Kongu Engineering College
20. File Write
The file write operations can be
performed by the functions fprintf() and
fputs() with similarities to read
operations.
Function Description
fprintf()
Similar to printf(), this function use
formatted string and varible arguments
list to print output to the file.
fputs()
Prints the whole line in the file and a
newline at the end.
fputc() Prints a single character into the file.
fputw() Prints a number to the file.
fwrite()
This functions write the specified
amount of bytes to the binary file.
20
P.Ananthi, Asssistant Professor, Kongu Engineering College
21. Write functions
Function Prototype Return Value Example Explanation
fputc
int fputc(int character,
FILE *stream);
Success: written
character, EOF on error
c FILE *filePointer =
fopen("example.txt",
"w"); int result =
fputc('A', filePointer);
fclose(filePointer);
Writes a character to
the specified file
stream.
fputs
int fputs(const char *str,
FILE *stream);
Success: non-negative,
EOF on error
c FILE *filePointer =
fopen("example.txt",
"w"); int result =
fputs("Hello, File!",
filePointer);
fclose(filePointer);
Writes a string to the
specified file stream.
21
P.Ananthi, Asssistant Professor, Kongu Engineering College
22. fprintf
int
fprintf(FILE *stream,
const char *format,
...);
Number
of characters
written
c FILE *filePointer = fopen("example.txt", "w");
int result = fprintf(filePointer, "Value: %d",
42); fclose(filePointer);
Writes
formatted output
to the specified
file stream.
fwrite
size_t fwrite(const void
*ptr, size_t size, size_t
count, FILE *stream);
Number of
items written
c FILE *filePointer = fopen("example.bin", "wb");
int array[5] = {1, 2, 3, 4,
5}; fwrite(array, sizeof(int),
5, filePointer); fclose(filePointer);
Writes data
from the specified
buffer to the file
stream.
fputw
int fputw(int
word, FILE *stream);
Write a binary
word (non-
negative
on success,
EOF on error)
c FILE *filePointer = fopen("example.bin", "wb");
int word = 42; int result
= fputw(word, filePointer); fclose(filePointer);
Writes a
binary word
(integer) to the file
stream
22
P.Ananthi, Asssistant Professor, Kongu Engineering College
23. File Writing using Buffer
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 1024 // Define
the buffer size
int main() {
FILE *file;
char buffer[BUFFER_SIZE];
char data[] = "This is an example of
writing data using a buffer.";
file = fopen("example.txt", "w");
if (file == NULL) {
printf("File could not be
opened.n");
return 1;
}
strcpy(buffer, data);
fwrite(buffer, sizeof(char), strlen(buffe
r), file);
fclose(file);
printf("Data written to file
successfully.n");
return 0;
}
23
P.Ananthi, Asssistant Professor, Kongu Engineering College
24. File Read
The file read operation in C can be performed
using functions fscanf() or fgets(). Both the
functions performed the same operations as that
of scanf and gets but with an additional parameter,
the file pointer.
fscanf()
Use formatted string and
variable arguments list to take
input from a file.
fgets()
Input the whole line from the
file.
fgetc()
Reads a single character from
the file.
fgetw() Reads a number from a file.
fread()
Reads the specified bytes of
data from a binary file.
24
P.Ananthi, Asssistant Professor, Kongu Engineering College
25. Function Prototype Return Value Example Explanation
fgetc
int fgetc(FILE
*stream);
Read character (or
EOF on error/end-
of-file)
c FILE *filePointer =
fopen("example.txt",
"r"); int ch =
fgetc(filePointer);
fclose(filePointer);
Reads a character
from the specified
file stream.
fgets
char *fgets(char *str,
int size, FILE *stream);
Success: str, NULL
on error/end-of-
file
c FILE *filePointer =
fopen("example.txt",
"r"); char buffer[100];
fgets(buffer,
sizeof(buffer),
filePointer);
fclose(filePointer);
Reads a line from
the specified file
stream into the
given buffer.
25
P.Ananthi, Asssistant Professor, Kongu Engineering College
26. fscanf
int fscanf(FILE
*stream, const char
*format, ...);
Number of input
items assigned
c FILE *filePointer =
fopen("example.txt", "r");
int value; fscanf(filePointer,
"%d", &value);
fclose(filePointer);
Reads formatted
input from the
specified file stream.
fread
size_t fread(void
*ptr, size_t size,
size_t count, FILE
*stream);
Number of items
read
c FILE *filePointer =
fopen("example.bin", "rb");
int array[5]; fread(array,
sizeof(int), 5, filePointer);
fclose(filePointer);
Reads data from the
file stream into the
specified buffer.
fgetw
int fgetw(FILE
*stream);
Read a binary word
(or EOF on
error/end-of-file)
c FILE *filePointer =
fopen("example.bin", "rb");
int word = fgetw(filePointer);
fclose(filePointer);
Reads a binary word
(integer) from the file
stream.
26
P.Ananthi, Asssistant Professor, Kongu Engineering College
27. File Reading using Buffer
#include <stdio.h>
#define BUFFER_SIZE 1024 // Define the buffer size
int main() {
FILE *file;
char buffer[BUFFER_SIZE];
file = fopen("example.txt", "r");
if (file == NULL) {
printf("File could not be opened.n");
return 1;
}
while (fgets(buffer, BUFFER_SIZE, file) !=
NULL) {
printf("Data read from file: %s",
buffer);
}
fclose(file);
return 0;
}
27
P.Ananthi, Asssistant Professor, Kongu Engineering College
28. File Handling functions
ferror function
FILE *file = fopen("example.txt",
"r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
fclose function
if (fclose(file) != 0) {
perror("Error closing file");
return 1;
}
28
P.Ananthi, Asssistant Professor, Kongu Engineering College
29. File Handling functions
fwrite function
size_t items_written = fwrite(buffer,
sizeof(char), strlen(buffer), file);
if (items_written != strlen(buffer)) {
perror("Error writing to file");
return 1;
}
fread function
size_t items_read = fread(buffer,
sizeof(char), BUFFER_SIZE, file);
if (items_read < BUFFER_SIZE) {
if (feof(file)) {
// End of file reached
} else if (ferror(file)) {
perror("Error reading from file");
return 1;
}
}
29
P.Ananthi, Asssistant Professor, Kongu Engineering College
30. File Handling functions
ferror function
if (ferror(file)) {
perror("Error reading from
file");
return 1;
}
feof function
if (feof(file)) {
// End of file reached
}
30
P.Ananthi, Asssistant Professor, Kongu Engineering College
31. Manipulating file position
fseek Function
• The fseek function in C is used to move the file
position indicator to a specified location within
the file. It allows you to set the position for the
next read or write operation.
int fseek(FILE *stream, long offset, int whence);
• stream: A pointer to a FILE object,
representing the file.
• offset: Number of bytes to move the file
position indicator.
• whence: Specifies the reference point for the
offset (SEEK_SET, SEEK_CUR, or SEEK_END).
Example
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
fseek(file, 10, SEEK_SET);
fclose(file);
return 0;
}
31
P.Ananthi, Asssistant Professor, Kongu Engineering College
32. Manipulating file position
ftell Function
• The ftell function returns the current file
position indicator's position in the specified file. It
is often used to determine the current position
before using fseek
long ftell(FILE *stream);
• stream: A pointer to a FILE object representing
the file.
Example
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Perform read operations
// Get the current position in the file
long position = ftell(file);
printf("Current position in file: %ldn", position);
fclose(file);
return 0;
}
32
P.Ananthi, Asssistant Professor, Kongu Engineering College
33. Manipulating file position
rewind Function
• The rewind function is a shorthand way of
moving the file position indicator to the beginning
of the file. It is equivalent to calling fseek with an
offset of 0 from the beginning (SEEK_SET).
void rewind(FILE *stream);
• stream: A pointer to a FILE object representing
the file.
Example
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Perform read or write operations
// Move the file position indicator to the beginning of the file
rewind(file);
fclose(file);
return 0;
}
33
P.Ananthi, Asssistant Professor, Kongu Engineering College
34. Other handling function
remove function
• The remove function in C is used to delete a file from the file
system.
int remove(const char *filename);
• filename: A string containing the name of the file to be
deleted.
Example
#include <stdio.h>
int main() {
if (remove("example.txt") != 0) {
perror("Error deleting file");
return 1;
}
printf("File deleted successfully.n");
return 0;
}
34
P.Ananthi, Asssistant Professor, Kongu Engineering College
35. Other handling function
rename function
• The rename function is used to change the name of a
file.
int rename(const char *oldname, const char *newname);
• oldname: A string containing the current name of the
file.
• newname: A string containing the new name for the file.
Example
#include <stdio.h>
int main() {
if (rename("oldname.txt", "newname.txt") != 0) {
perror("Error renaming file");
return 1;
}
printf("File renamed successfully.n");
return 0;
}
35
P.Ananthi, Asssistant Professor, Kongu Engineering College
36. Other handling function
tmpfile function
• The tmpfile function is used to create a temporary
file that is automatically deleted when the program
terminates..
FILE *tmpfile(void);
Example
#include <stdio.h>
int main() {
FILE *tempFile = tmpfile();
if (tempFile == NULL) {
perror("Error creating temporary file");
return 1;
}
// Perform read or write operations on the temporary file
fclose(tempFile);
// The temporary file is automatically deleted when the
program terminates
return 0;
}
36
P.Ananthi, Asssistant Professor, Kongu Engineering College
37. Preprocessor directives
• In C programming, preprocessor directives are special commands that begin with a hash symbol
(#). Two commonly used preprocessor directives are #define and #include.
1. #define Directive: macros are created using the #define directive. Macros can be defined with or
without arguments, providing flexibility for code generation and abstraction.
2. #include Directive:
37
P.Ananthi, Asssistant Professor, Kongu Engineering College
38. Preprocessor directives
#include Directive
• The #include directive is used to include the contents
of another file in the current source file. This is often
used for including header files that contain function
prototypes, declarations, or macro definitions.
#include <header_file.h>
// math_functions.h
#ifndef MATH_FUNCTIONS_H
#define MATH_FUNCTIONS_H
int add(int a, int b);
int subtract(int a, int b);
#endif // MATH_FUNCTIONS_H
// main_program.c
#include <stdio.h>
#include "math_functions.h"
int main() {
int result_add = add(10, 5);
int result_subtract = subtract(10, 5);
printf("Addition result: %dn", result_add);
printf("Subtraction result: %dn", result_subtract);
return 0;
}
38
P.Ananthi, Asssistant Professor, Kongu Engineering College
39. Preprocessor directives
#define Directive
• The #define directive is used to create symbolic constants or
macros. It is a way to give a name to a constant value or a piece
of code and allows for easy modification of values throughout the
code.
#define identifier replacement
#include <stdio.h>
// Define a constant
#define PI 3.14159
int main() {
// Use the defined constant
double radius = 5.0;
double area = PI * radius * radius;
printf("Area of the circle: %fn", area);
return 0;
}
P.Ananthi, Asssistant Professor, Kongu Engineering College 39
40. Preprocessor directives
Macro without arguments
• A macro without arguments is a simple text substitution. It is
often used to define constants or to create simple code snippets.
#define MACRO_NAME replacement
Example
#include <stdio.h>
// Define a constant macro
#define PI 3.14159
int main() {
// Use the macro
double radius = 5.0;
double area = PI * radius * radius;
printf("Area of the circle: %fn", area);
return 0;
}
40
P.Ananthi, Asssistant Professor, Kongu Engineering College
41. Preprocessor directives
Macro with arguments
• Macros with arguments are more versatile and can be used for code
generation. They are defined with parameters, and these parameters
are replaced with actual values when the macro is invoked.
#define MACRO_NAME(parameter1, parameter2, ...)
replacement
Example
#include <stdio.h>
// Macro with arguments
#define SQUARE(x) ((x) * (x))
int main() {
// Use the macro
int result = SQUARE(5);
printf("Square of 5 is: %dn", result);
return 0;
}
41
P.Ananthi, Asssistant Professor, Kongu Engineering College