6. File Input/Output
6.1 File Open
C allows us to read data from text/binary files using fopen().
FILE ∗fopen(char name[], char mode[])
– mode can be "r" (read only),"w" (write only),"a" (append) among other options. "b" can be    appended for binary files.
– fopen returns a pointer to the file stream if it exists or NULL otherwise.
– We don’t need to know the details of the FILE data type.
Important: The standard input and output are also FILE *datatypes (stdin, stdout).
Important: stderr corresponds to standard error output(different from stdout).
int fclose(FILE ∗fp)
– closes the stream (releases OS resources).
– fclose() is automatically called on all open files when program terminates.
6.2 File Input
int getc(FILE ∗fp)
– reads a single character from the stream.
– returns the character read or EOF on error/end of file.
– Note: getchar simply uses the standard input to read a character.
   We can implement it as follows: #define getchar() getc(stdin)
char[] fgets(char line[], int maxlen, FILE ∗fp)
– reads a single line (upto maxlen characters) from the input stream (including linebreak).
– returns a pointer to the character array that stores the line (read-only)
– return NULL if end of stream.
Example: fgets
/* fgets: get at most n chars from a file */
char *fgets(char *s, int n, FILE *fp)
     register int c;
     register char *cs;
     cs = s;
     while (--n > 0 && (c == getc(fp)) != EOF)
          if ((*cs++ = c) == ‘\n’)
     *cs = ‘\0’;

     return (c == EOF && cs == s) ? NULL : s;
6.3 File Output
int putc(int c, FILE ∗fp)
– writes a single character c to the output stream. returns the character written or EOF on error.
– Note: putchar simply uses the standard output to write a character.
   We can implement it as follows: #define putchar(c) putc(c, stdout)
int fputs(char line[], FILE ∗fp)
– writes a single line to the output stream.
– returns zero on success, EOF otherwise.
int fscanf(FILE ∗fp, char format[], arg1, arg2)
– similar to scanf, sscanf
– reads items from input stream fp.
Example: fputs
/* fputs: put string s on file fp */
int fputs(char *s, FILE *fp)
    int c;
    while (c = *s++)
        putc(c, fp);

return ferror(fp) ? EOF : 0;
Example: concatenate files
#include <stdio.h>

/* cat: concatenate files */
int main(int argc, char *argv[])
    FILE *fp;
    void filecopy(FILE *, FILE *);

    if (argc == 1) filecopy(stdin, stdout);
    else {
        while(--argc > 0) {
             if ((fp = fopen(*++argv, "r")) == NULL) {
                printf("cat: can’t open %s\n", *argv);
                return 1;
            else {
                filecopy(fp, stdout);

    return 0;

/* filecopy: copy file ifp to file ofp */
void filecopy(FILE *ifp, FILE *ofp)
    int c;
    while ((c = getc(ifp)) != EOF)
        putc(c, ofp);
이전페이지 / 7 / 다음페이지