|
|
coherent
fopen() STDIO Function fopen()
Open a stream for standard I/O
#include <stdio.h>
FFIILLEE *ffooppeenn (_n_a_m_e, _t_y_p_e) cchhaarr *_n_a_m_e, *_t_y_p_e;
fopen allocates and initializes a FILE structure, or stream;
opens or creates the file name; and returns a pointer to the
structure for use by other STDIO routines. name refers to the
file to be opened. type is a string that consists of one or more
of the characters ``rwa'', to indicate the mode of the string, as
follows:
rr Read; error if file not found
ww Write; truncate if found, create if not found
aa Append to end of file; no truncation, create if not found
rr+ Read and write; no truncation, error if not found
ww+ Write and read; truncate if found, create if not found
aa+ Append and read; no truncation, create if not found
The modes that contain `a' set the seek pointer to point at the
end of the file; all other modes set it to point at the beginning
of the file. Modes that contain `+' both read and write;
however, a program must call ffsseeeekk or rreewwiinndd before it switches
from reading to writing or vice versa.
***** Example ***** This example copies argv[1] to argv[2] using
STDIO routines. It demonstrates the functions fopen, fread,
fwrite, fclose, and feof.
#include <stdio.h>
/* BUFSIZ is defined in stdio.h */
char buf[BUFSIZ];
void fatal(message)
char *message;
{
fprintf(stderr, "copy: %s\n", message);
exit(1);
}
COHERENT Lexicon Page 1
fopen() STDIO Function fopen()
main(argc, argv)
int argc; char *argv[];
{
register FILE *ifp, *ofp;
register unsigned int n;
if (argc != 3)
fatal("Usage: copy source destination");
if ((ifp = fopen(argv[1], "r")) == NULL)
fatal("cannot open input file");
if ((ofp = fopen(argv[2], "w")) == NULL)
fatal("cannot open output file");
while ((n = fread(buf, 1, BUFSIZ, ifp)) != 0) {
if (fwrite(buf, 1, n, ofp) != n)
fatal("write error");
}
if (!feof(ifp))
fatal("read error");
if (fclose(ifp) == EOF || fclose(ofp) == EOF)
fatal("cannot close");
exit(0);
}
***** See Also *****
fclose(), fdopen(), freopen(), STDIO
***** Diagnostics *****
fopen returns NULL if it cannot allocate a FILE structure, if the
type string is nonsense, or if the call to open or creat fails.
Currently, only 20 FILE structures can be allocated per program,
including stdin, stdout, and stderr.
***** Notes *****
Many operating systems recognize a `b' modifier to the type argu-
ment; this indicates that the file contains binary information,
and lets the operating system handle ``funny characters'' cor-
rectly. COHERENT has no need of such a modifier, so if you ap-
pend `b' to type, it will be ignored. This modifier, however, is
recognized by numerous other operating systems, including MS-DOS,
OS/2, and GEMDOS. If you expect to port developed code to any of
these operating systems, files should append the `b' to type.
COHERENT Lexicon Page 2
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.