fopen() STDIO Function fopen()
Open a stream for standard I/O
#include <stdio.h>
FILE *fopen (name, type) char *name, *type;
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:
r Read; error if file not found
w Write; truncate if found, create if not found
a Append to end of file; no truncation, create if not found
r+ Read and write; no truncation, error if not found
w+ Write and read; truncate if found, create if not found
a+ 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 fseek or rewind 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