SlideShare a Scribd company logo
1 of 41
File Handling
1
P.Ananthi, Asssistant Professor, Kongu Engineering College
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
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
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
File
Text file
Binary
File
5
P.Ananthi, Asssistant Professor, Kongu Engineering College
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

More Related Content

What's hot (20)

C pointers
C pointersC pointers
C pointers
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocation
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
5bit field
5bit field5bit field
5bit field
 
Verilog Lecture2 thhts
Verilog Lecture2 thhtsVerilog Lecture2 thhts
Verilog Lecture2 thhts
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
File handling-c
File handling-cFile handling-c
File handling-c
 
8086 Microprocessor
8086 Microprocessor8086 Microprocessor
8086 Microprocessor
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
 
C Pointers
C PointersC Pointers
C Pointers
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
캐쉬 일관성 Msi, mesi 프로토콜 흐름
캐쉬 일관성   Msi, mesi 프로토콜 흐름캐쉬 일관성   Msi, mesi 프로토콜 흐름
캐쉬 일관성 Msi, mesi 프로토콜 흐름
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
8255 Introduction
8255 Introduction8255 Introduction
8255 Introduction
 
Pointers
PointersPointers
Pointers
 

Similar to File Handling.pptx

File handing in C
File handing in CFile handing in C
File handing in Cshrishcg
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in pythonnitamhaske
 
File management
File managementFile management
File managementsumathiv9
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptxqover
 
358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16sumitbardhan
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file editedLinga Lgs
 
File Handling and Preprocessor Directives
File Handling and Preprocessor DirectivesFile Handling and Preprocessor Directives
File Handling and Preprocessor DirectivesSelvaraj Seerangan
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdfbotin17097
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O YourHelper1
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by FaixanٖFaiXy :)
 

Similar to File Handling.pptx (20)

File handing in C
File handing in CFile handing in C
File handing in C
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
File management
File managementFile management
File management
 
Python file handling
Python file handlingPython file handling
Python file handling
 
637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
 
358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16
 
finally.c.ppt
finally.c.pptfinally.c.ppt
finally.c.ppt
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
 
File Handling and Preprocessor Directives
File Handling and Preprocessor DirectivesFile Handling and Preprocessor Directives
File Handling and Preprocessor Directives
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 

File Handling.pptx

  • 1. File Handling 1 P.Ananthi, Asssistant Professor, Kongu Engineering College
  • 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
  • 5. File Text file Binary File 5 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