Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Write a String to a File

C Language Examples - Write a String to a File

C Language Examples C Language Examples

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 C Language Examples