C Exercise 97
100 Classic C Language Examples
**Problem:** Input some characters from the keyboard and write them one by one to disk until a # is entered.
**Analysis:** None.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
#include
<
stdlib.h
int
main
(
)
{
FILE
fp
=
NULL;
char
filename
[
25
]
;
char
ch
;
printf
(
"
Enter the name of the file you want to save to:
\
n
"
)
;
gets
(
filename
)
;
if
(
(
fp
=
fopen
(
filename
,
"
w
"
)
)
==
NULL
)
{
printf
(
"
error: cannot open file!
\
n
"
)
;
exit
(
0
)
;
}
printf
(
"
Now you can enter the characters you want to save, ending with #:
\
n
"
)
;
getchar
(
)
;
while
(
(
ch
=
getchar
(
)
)
!='#'
)
{
fputc
(
ch
,
fp
)
;
}
fclose
(
fp
)
;
system
(
"
pause
"
)
;
return
0
;
}
The above example produces the following output:
Enter the name of the file you want to save to:
test.txt
You can now enter some characters you want to save, ending with #:
www.runoob.com
#