1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>12.2 I/O with File Pointers
</title>
10 <link href=
"sx12a.html" rev=precedes
>
11 <link href=
"sx12c.html" rel=precedes
>
12 <link href=
"sx12.html" rev=subdocument
>
15 <H2>12.2 I/O with File Pointers
</H2>
17 <p>For each of the I/O library functions we've been using so far,
18 there's a companion function
19 which accepts an additional file pointer argument
20 telling it where to read from or write to.
21 The companion function to
<TT>printf
</TT> is
<TT>fprintf
</TT>,
22 and the file pointer argument comes first.
23 To print a string to the
<TT>output.dat
</TT> file
24 we opened in the previous section,
27 fprintf(ofp,
"Hello, world!\n");
29 </p><p>The companion function to
<TT>getchar
</TT> is
<TT>getc
</TT>,
30 and the file pointer is its only argument.
31 To read a character from the
<TT>input.dat
</TT> file
32 we opened in the previous section,
38 </p><p>The companion function to
<TT>putchar
</TT> is
<TT>putc
</TT>,
39 and the file pointer argument comes last.
40 To write a character to
<TT>output.dat
</TT>,
45 </p><p>Our own
<TT>getline
</TT> function calls
<TT>getchar
</TT>
46 and so always reads the standard input.
47 We could write a companion
<TT>fgetline
</TT> function
48 which reads from an arbitrary file pointer:
50 #include
<stdio.h
>
52 /* Read one line from fp, */
53 /* copying it to line array (but no more than max chars). */
54 /* Does not place terminating \n in line array. */
55 /* Returns line length, or
0 for empty line, or EOF for end-of-file. */
57 int fgetline(FILE *fp, char line[], int max)
61 max = max -
1; /* leave room for '\
0' */
63 while((c = getc(fp)) != EOF)
75 if(c == EOF
&& nch ==
0)
82 </p><p>Now we could read one line from
<TT>ifp
</TT> by calling
86 fgetline(ifp, line, MAXLINE);
92 <a href=
"sx12a.html" rev=precedes
>prev
</a>
93 <a href=
"sx12c.html" rel=precedes
>next
</a>
94 <a href=
"sx12.html" rev=subdocument
>up
</a>
95 <a href=
"top.html">top
</a>
98 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
99 //
<a href=
"copyright.html">Copyright
</a> 1995-
1997
100 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>