0% found this document useful (0 votes)
2 views20 pages

File Handling in C

File handling in C allows programs to store and retrieve data using various operations such as creating, opening, reading, writing, and closing files. The fopen() function is used to create or open files, while fprintf() and fscanf() are used for writing to and reading from files, respectively. Additionally, standard input and output can be redirected to files, and special streams like stdin, stdout, and stderr are defined for handling input and output.

Uploaded by

Aakash Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

File Handling in C

File handling in C allows programs to store and retrieve data using various operations such as creating, opening, reading, writing, and closing files. The fopen() function is used to create or open files, while fprintf() and fscanf() are used for writing to and reading from files, respectively. Additionally, standard input and output can be redirected to files, and special streams like stdin, stdout, and stderr are defined for handling input and output.

Uploaded by

Aakash Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

File Handling

File Handling is the storing of data in a file using a program. In C programming


language, the programs store results, and other data of the program to a file
using file handling in C. Also, we can extract/fetch data from a file to work with it
in the program.
The operations that you can perform on a File in C are −
•Creating a new file
•Opening an existing file
•Reading data from an existing file
•Writing data to a file
•Moving data to a specific location on the file
•Closing the file
What is a file?

• A named collection of data, stored in secondary


storage (typically).
• Typical operations on files:
– Open
– Read
– Write
– Close
• How is a file stored?
– Stored as sequence of bytes, logically contiguous (may not be
physically contiguous on disk).
Creating or opening file using fopen()

The fopen() function is used to create a new file or open an existing file in C.
The fopen function is defined in the stdio.h header file.
Now, lets see the syntax for creation of a new file or opening a file
file = fopen(“file_name”, “mode”)
This is a common syntax for both opening and creating a file in C.
Parameters
file_name − It is a string that specifies the name of the file that is to be
opened or created using the fopen method. mode: It is a string (usually a
single character )
that specifies the mode in which the file is to be opened. There are various
modes available to open a file in C, we will learn about all of them later in this
article.
When will a file be created?
The fopen function will create a new file when it will not find any file of
the specified name in the specified location. Else, if the file is found it
will be opened with the mode specified.
Let’s see can example which will make the concept clear, Suppose we
are opening a file named hello.txt using the fopen function. The
following will be the statement,
file = fopen(“hello.txt”, “w”)
This will search for a file named hello.txt in the current directory. If the
file exists, it will open the file otherwise it will create a new file named
“hello.txt” and open it with write mode (specified using “w”).
– The last byte of a file contains the end-of-file character (EOF),
with ASCII code 1A (hex).
– While reading a text file, the EOF character can be checked to
know the end.
• Two kinds of files:
– Text :: contains ASCII codes only
– Binary :: can contain non-ASCII characters
• Image, audio, video, executable, etc.
• To check the end of file here, the file size value (also stored on
disk) needs to be checked.
File handling in C

• In C we use FILE * to represent a pointer to a file.


• fopen is used to open a file. It returns the special value NULL
to indicate that it is unable to open the file.

FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE
CREATION”);
/* DO SOMETHING */
}
Modes for opening files

• The second argument of fopen is the mode in


which we open the file. There are three modes.
"r" opens a file for reading.

"w" creates a file for writing, and writes over all previous
contents (deletes the file so be careful!).

"a" opens a file for appending – writing on the end of the


file.
• We can add a “b” character to indicate that the file is a
binary file.
– “rb”, “wb” or “ab”

fptr = fopen (“xyz.jpg”, “rb”);


The exit() function

• Sometimes error checking means we want an


"emergency exit" from a program.
• In main() we can use return to stop.
• In functions we can use exit() to do this.
• Exit is part of the stdlib.h library.

exit(-1);
in a function is exactly the same as

return -1;
in the main routine
Usage of exit( )

FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE
CREATION”);
/* Do something */
exit(-1);
}
………
Writing to a file using fprintf( )

• fprintf() works just like printf() and


sprintf()
except that its first argument is a file pointer.

FILE *fptr;
Fptr = fopen ("file.dat","w");
/* Check it's open */

fprintf (fptr, "Hello World!\n");


fprintf (fptr, “%d %d”, a, b);
Reading Data Using fscanf( )

• We also read data from a file using


fscanf().
FILE *fptr;
Fptr = fopen (“input.dat”, “r”);
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in
opening file \
n”);
}
fscanf (fptr, “%d
%d”,&x, &y);
Reading lines from a file using fgets( )

We can read a string using fgets().

FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n",line);
}

fgets() takes 3 arguments – a string, maximum


number of characters to read, and a file pointer.
It returns NULL if there is an error (such as EOF).
Closing a file

• We can close a file simply using fclose() and


the file pointer.

FILE *fptr;
char filename[]= "myfile.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf ("Cannot open file to write!\n");
exit(-1);
}
fprintf (fptr,"Hello World of filing!\n");
fclose (fptr);
Three special streams

• Three special file streams are defined in the <stdio.h>


header
– stdin reads input from the keyboard
– stdout send output to the screen
– stderr prints errors to an error device (usually also the screen)

• What might this do?

fprintf (stdout,"Hello World!\n");


An example program

#include <stdio.h>
main()
{
int i;

fprintf(stdout,"Give value of i \n");


fscanf(stdin,"%d",&i);
fprintf(stdout,"Value of i=%d \n",i);
fprintf(stderr,"No error: But an example to
show error message.\n");
}
Give value of i
15
Value of i=15
No error: But an example to show error message.
Input File & Output File redirection

• One may redirect the standard input and standard


output to other files (other than stdin and
stdout).
• Usage: Suppose the executable file is a.out:

$ ./a.out <in.dat >out.dat

scanf() will read data inputs from the file


“in.dat”, and printf() will output results on the
file “out.dat”.
A Variation

$ ./a.out <in.dat >>out.dat

scanf() will read data inputs from the file “in.dat”,


and printf() will append results at the end of the
file “out.dat”.
Reading and Writing a character

• A character reading/writing is equivalent


to reading/writing a byte.
int getchar( );
stdin, stdout
int putchar(int
c);
int fgetc(FILE *fp); file
int fputc(int c, FILE *fp);

• Example:
char c;
c = getchar();
putchar(c);
Example: use of getchar() &
putchar()
#include <stdio.h>
main()
{
int c;

printf("Type text and press return to


see it again \n");
printf("For exiting press <CTRL D> \n");
while((c = getchar()) != EOF)
putchar(c);
}

You might also like