0% found this document useful (0 votes)
15 views

Introduction to File Handling

Anu Cutie dosti ho ya relationship ego hamesa side rakhna hota hai Verna ego ka chalta sab khtm ho jata hai ?Cutie Tumha gussa Krna hai pyar Krna hai mera sa kro but kisi dusra ko kuch nh batao .Remember cutie nonu is always there for you ??Cutie Tumha gussa Krna hai pyar Krna hai mera sa kro but kisi dusra ko kuch nh batao .

Uploaded by

sy1973393
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Introduction to File Handling

Anu Cutie dosti ho ya relationship ego hamesa side rakhna hota hai Verna ego ka chalta sab khtm ho jata hai ?Cutie Tumha gussa Krna hai pyar Krna hai mera sa kro but kisi dusra ko kuch nh batao .Remember cutie nonu is always there for you ??Cutie Tumha gussa Krna hai pyar Krna hai mera sa kro but kisi dusra ko kuch nh batao .

Uploaded by

sy1973393
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT-V

INTRODUCTION TO FILE HANDLING


Why do we need File Handling in C?
File handling in C stores data of our program in our local store,
which can be used at any time because as the execution of a program
completes, our data is lost. Therefore, we need to save our data in
any file form - text or binary files.
A few features of using files
Reusability: Data stored in files can be used repeatedly.

Portability: Files enable data transfer between different systems.

Efficient: Quick access to stored data.

Storage Capacity: Large amounts of data can be stored beyond the


constraints of RAM.
Types of Files in C
We will be working with two types of files: -

✓ Text file
✓ Binary file

Let’s understand them in brief -

Text file - The user can create these files easily while handling files in C. It stores
information in the form of ASCII characters internally, and when the file is opened, the
content is readable by humans. It can be created by any text editor with a .txt or .rtf (rich
text)extension. Since text files are simple, they can be edited by any text editor like
Microsoft Word, Notepad, Apple Text Edit, etc.

Binary file - It stores information in the form of 0’s or 1’s, and it is saved with the .bin
extension, taking less space. Since it is stored in a binary number system format, it is not
readable by humans. Therefore it is more secure than a text file.
C File Operations
There are different kinds of file operations in C.
✓ Creating a new file
✓ Opening an existing file
✓ Writing data to a file
✓ Reading data from an existing file.
✓ Moving data to a specific location on the file
✓ Closing the file
S.No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
File Pointer in C
When you want to perform file operations in C like reading from or writing to a file, you
need a way to reference that file within your program. This reference is provided by the
file pointer. The file pointer stores the address of a FILE structure, which contains details
about the file, like its name, its current position, its size, etc.

Syntax of File Pointer:


FILE *pointer_name;

FILE is a predefined data type in C, defined in the stdio.h header file. It represents a file
type.

* indicates that pointer_name is a pointer.

pointer_name can be any valid variable name, and it will become the name of the file
pointer.
For example, if you want to declare a file pointer named fptr, you'd write:

FILE *fptr;

Later on, when you open a file, you will use functions like fopen() which
will return a file pointer, and you can assign this to your declared file
pointer:

fptr = fopen("filename.txt", "r");

This fptr can then be used with other functions to perform various
operations on the file "filename.txt".
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
//open a file
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
fptr = fopen("example.txt", "r"); // Open the file in read mode
if (fptr == NULL) {
printf("Error in opening the file.\n");
return 1; // Exit the program if file can't be opened
}
printf("File opened successfully.\n");
fclose(fptr); // It's a good practice to close the file after operation
return 0;
}
Create a File in C
#include <stdio.h>
int main() {
FILE *filePtr;
// Attempt to open the file for writing
filePtr = fopen("example.txt", "w");
// Check if the file was opened successfully
if (filePtr == NULL) {
printf("Error opening or creating the file!\n");
return 1;
}
printf("File opened or created successfully.\n");
// Don't forget to close the file
fclose(filePtr);

return 0;
}
int main() {
FILE *fptr;
int num = 42;
// Opening the file in write mode
fptr = fopen("numbers.txt", "w");
// Writing data to the file using different functions
fprintf(fptr, "The number is: %d\n", num);
fputs("This is a test line.\n", fptr);
fputc('A', fptr);
fputw(100, fptr);

// Closing the file


fclose(fptr);

return 0;
}
Example 1: Program to Create a File, Write in it, And Close the File
#include <stdio.h>
#include <string.h>

int main()
{
// Declare a pointer for the file
FILE *diaryFile;

// Content to be written into the file


char diaryEntry[150] = "Diary of a Programmer - "
"Today, I learned about file handling in C, "
"which feels like unlocking a new programming superpower.";

// Opening the file "LearningDiary.txt" in write mode ("w")


diaryFile = fopen("LearningDiary.txt", "w");

// Verifying if the file was successfully opened


if (diaryFile == NULL) {
printf("LearningDiary.txt file could not be opened.\n");
} else {
printf("File opened successfully.\n");

// Checking if there's content to write


if (strlen(diaryEntry) > 0) {

// Writing the diary entry to the file


fputs(diaryEntry, diaryFile);
fputs("\n", diaryFile); // New line at the end of the entry
}

// Closing the file to save changes


fclose(diaryFile);

printf("Diary entry successfully recorded in LearningDiary.txt\n");


printf("File closed. Diary saved.\n");
}

return 0;
}
➢ C fprintf() and fscanf()

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It
sends formatted output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file.txt", "w"); //opening file
fprintf(fp, "Hello file by fprintf...\n"); //writing data into file
fclose(fp);//closing file
}
➢ C fputc() and fgetc()
Writing File : fputc() function
The fputc() function is used to write a single character into
file. It outputs a character to a stream.
Syntax:
OUTPUT – File1.txt
1.int fputc(int c, FILE *stream)
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It
gets a character from the stream. It returns EOF at the end of
file.
Syntax:
int fgetc(FILE *stream)

Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}

OUTPUT –
myfile.txt
➢ C fseek() function
The fseek() function is used to set the file pointer to the specified
offset. It is used to write data into file at desired location.

Syntax:
int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence:


SEEK_SET, SEEK_CUR and SEEK_END.
For Example:-
#include <stdio.h>
void main(){
FILE *fp;
OUTPUT
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);

fseek( fp, 7, SEEK_SET );


fputs("sonoo jaiswal", fp);
fclose(fp);
}
For Example:-
#include <stdio.h>
void main(){ OUTPUT
FILE *fp;

fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);

fseek( fp, 7, SEEK_SET );


fputs("sonoo jaiswal", fp);
fclose(fp);
}
➢ C rewind() function
The rewind() function sets the file pointer at the
beginning of the stream. It is useful if you have to use stream
many times.

Syntax:
void rewind(FILE *stream)

Example:
File: file.txt
this is a simple text

File: rewind.c
For Example
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");

while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
OUTPUT
fclose(fp);
getch();
}

As you can see, rewind() function moves the file pointer


at beginning of the file that is why "this is simple text"
is printed 2 times. If you don't call rewind() function,
"this is simple text" will be printed only once.
C ftell() function
The ftell() function returns the current file position of the
specified stream. We can use ftell() function to get the total size
of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.

Syntax:
long int ftell(FILE *stream)

Example:
File: ftell.c
For Example
#include <stdio.h> OUTPUT
#include <conio.h>
void main (){
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
getch();
}
C Preprocessor Directives
The C preprocessor is a micro
processor that is used by compiler to
transform your code before
compilation. It is called micro
preprocessor because it allows us to
add macros.
Note: Proprocessor direcives are
executed before compilation.

All preprocessor directives starts


with hash # symbol.
Let's see a list of preprocessor directives.
➢ #include
➢ #define
➢ #undef
➢ #ifdef
➢ #ifndef
➢ #if
➢ #else
➢ #elif
➢ #endif
➢ #error
➢ #pragma
C Macros
A macro is a segment of code which is replaced by the
value of macro. Macro is defined by #define directive.
There are two types of macros:

1. Object-like Macros
2. Function-like Macros

1. Object-like Macros
The object-like macro is an identifier that is replaced by
value. It is widely used to represent numeric constants.

For example:
#define PI 3.14
Here, PI is the macro name which will be replaced by the
value 3.14.
Function-like Macros
The function-like macro looks like function call.

For example:
#define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.


Visit #define to see the full example of object-like and
function-like macros.
C Predefined Macros
ANSI C defines many predefined macros that can be used
in c program.
No. Macro Description
1 _DATE_ represents current date in "MMM DD
YYYY" format.
2 _TIME_ represents current time in
"HH:MM:SS" format.
3 _FILE_ represents current file name.
4 _LINE_ represents current line number.
5 _STDC_ It is defined as 1 when compiler
complies with the ANSI standard.
C predefined macros example

File: simple.c OUTPUT


#include<stdio.h>
int main(){
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}
THANKYOU
THANK YOU

You might also like