File Handling in C
File Handling in C
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
FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE
CREATION”);
/* DO SOMETHING */
}
Modes for opening files
"w" creates a file for writing, and writes over all previous
contents (deletes the file so be careful!).
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( )
FILE *fptr;
Fptr = fopen ("file.dat","w");
/* Check it's open */
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n",line);
}
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
#include <stdio.h>
main()
{
int i;
• Example:
char c;
c = getchar();
putchar(c);
Example: use of getchar() &
putchar()
#include <stdio.h>
main()
{
int c;