C Library Function - fopen()
Description
C Library Function **FILE *fopen(const char filename, const char mode) using the given mode mode Open filename the file pointed to by .
Declaration
Below is the declaration of the fopen() function.
FILE *fopen(const char *filename, const char *mode)
Parameters
- filename -- a string that specifies the name of the file to open.
- mode -- a string that specifies the file access mode, which can be one of the values in the following table:
| Mode | Description |
|---|---|
| "r" | Open a file for reading. The file must exist. |
| "w" | Create an empty file for writing. If a file with the same name already exists, its contents are deleted and the file is treated as a new empty file. |
| "a" | Append to a file. Write operations append data to the end of the file. If the file does not exist, it is created. |
| "r+" | Open a file for updating, both reading and writing. The file must exist. |
| "w+" | Create an empty file for reading and writing. |
| "a+" | Open a file for reading and appending. |
Return Value
This function returns a FILE pointer. Otherwise, it returns NULL and sets the global variable errno to indicate the error.
Example
The following example demonstrates the use of the fopen() function.
Example
#include
<
stdio.h
#include
<
stdlib.h
int
main
(
)
{
FILE
fp;
fp
=
fopen
(
"
file.txt
"
,
"
w+
"
)
;
fprintf
(
fp
,
"
%s %s %s %d
"
,
"
We
"
,
"
are
"
,
"
in
"
,
2014
)
;
fclose
(
fp
)
;
return
(
0
)
;
}
Let's compile and run the above program; this will create a file with the following content file.txt:
We are in 2014
Now let us use the following program to view the content of the file above:
#include
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
C Standard Library -