C Language Examples - Write a String to a File
Write a string to a file.
Example
#include
<
stdio.h
#include
<
stdlib.h/* exit() function */
int
main
(
)
{
char
sentence
[
1000
]
;
FILE
fptr
;
fptr
=
fopen
(
"
runoob.txt
"
,
"
w
"
)
;
if
(
fptr
==
NULL
)
{
printf
(
"
Error!
"
)
;
exit
(
1
)
;
}
printf
(
"
Enter a string:
\
n
"
)
;
fgets
(
sentence
,
(
sizeof
sentence
/
sizeof
sentence
[
0
]
)
,
stdin
)
;
fprintf
(
fptr
,
"
%s
"
,
sentence
)
;
fclose
(
fptr
)
;
return
0
;
}
The output is:
Input string:
runoob.com
Open the file runoob.txt:
$ cat runoob.txt
runoob.com
C Language Examples