版本5和6间的区别
于2006-05-22 20:35:49修订的的版本5
大小: 2586
编辑: czk
备注:
于2007-07-18 20:51:00修订的的版本6
大小: 2655
编辑: czk
备注:
删除的内容标记成这样。 加入的内容标记成这样。
行号 1: 行号 1:
## page was renamed from Input and Output/7.7 Line Input and Output

Navigation(slides)

7.7 Line Input and Output

The standard library provides an input and output routine fgets that is similar to the getline function that we have used in earlier chapters:

   char *fgets(char *line, int maxline, FILE *fp)

fgets reads the next input line (including the newline) from file fp into the character array line; at most maxline-1 characters will be read. The resulting line is terminated with '\0'. Normally fgets returns line; on end of file or error it returns NULL. (Our getline returns the line length, which is a more useful value; zero means end of file.)

For output, the function fputs writes a string (which need not contain a newline) to a file:

   int fputs(char *line, FILE *fp)

It returns EOF if an error occurs, and non-negative otherwise.

The library functions gets and puts are similar to fgets and fputs, but operate on stdin and stdout. Confusingly, gets deletes the terminating '\n', and puts adds it.

To show that there is nothing special about functions like fgets and fputs, here they are, copied from the standard library on our system:

   1    /* fgets:  get at most n chars from iop */
   2    char *fgets(char *s, int n, FILE *iop)
   3    {
   4        register int c;
   5        register char *cs;
   6 
   7        cs = s;
   8        while (--n > 0 && (c = getc(iop)) != EOF)
   9            if ((*cs++ = c) == '\n')
  10                break;
  11        *cs = '\0';
  12        return (c == EOF && cs == s) ? NULL : s;
  13    }
  14 
  15    /* fputs:  put string s on file iop */
  16    int fputs(char *s, FILE *iop)
  17    {
  18        int c;
  19 
  20        while (c = *s++)
  21            putc(c, iop);
  22        return ferror(iop) ? EOF : 0;
  23    }

For no obvious reason, the standard specifies different return values for ferror and fputs.

It is easy to implement our getline from fgets:

   1    /* getline:  read a line, return length */
   2    int getline(char *line, int max)
   3    {
   4        if (fgets(line, max, stdin) == NULL)
   5            return 0;
   6        else
   7            return strlen(line);
   8    }

Exercise 7-6. Write a program to compare two files, printing the first line where they differ.

Exercise 7-7. Modify the pattern finding program of Chapter 5 to take its input from a set of named files or, if no files are named as arguments, from the standard input. Should the file name be printed when a matching line is found?

Exercise 7-8. Write a program to print a set of files, starting each new one on a new page, with a title and a running page count for each file.

Navigation(siblings)

TCPL/7.7_Line_Input_and_Output (2008-02-23 15:37:06由localhost编辑)

ch3n2k.com | Copyright (c) 2004-2020 czk.