现在的位置: 首页 > 11 文件处理 > 设计导读 > 正文

【K&R C语言】第7章 输入与输出

2011年04月13日 11 文件处理, 设计导读 ⁄ 共 1534字 ⁄ 字号 暂无评论

本章将讲述标准库,介绍一些输入/输出函数、字符串处理函数

7.1 标准输入/输出 【A 将标准输入转换为小写字母】 
7.4 格式化输入—scanf函数 【B 简单计算器程序】
7.5 文件访问 【C 合并多个文件】
7.6 错误处理—stderr和exit 【合并多个文件,高级版本】 
7.7 行输入和行输出 【D getline函数】

7.1 标准输入/输出 【将标准输入转换为小写字母】

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <ctype.h>
 
int main()
{
    int c;
 
    while ((c = getchar()) != EOF)
        putchar(tolower(c));
    return 0;
}

7.4 格式化输入—scanf函数 【简单计算器程序】

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
 
int main()
{
    double sum, v;
 
    sum = 0;
    while (scanf("%lf", &v) == 1)
        printf("\t%.2f\n", sum += v);
    return 0;
}

7.5 文件访问 【合并多个文件】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
 
void filecopy(FILE *, FILE *);
 
/* cat: concatenate files, version 1 */
int main(int argc, char *argv[])
{
    FILE *fp;
 
    if (argc == 1)  /* no args; copy standard input */
        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);
                fclose(fp);
            }
    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.6 错误处理—stderr和exit 【合并多个文件,高级版本】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>
 
void filecopy(FILE *, FILE *);
 
/* cat: concatenate files, version 2 */
int main(int argc, char *argv[])
{
    FILE *fp;
    char *prog = argv[0]; /* program name for errors */
 
    if (argc == 1 ) /* no args; copy standard input */
        filecopy(stdin, stdout);
    else
        while (--argc > 0)
            if ((fp = fopen(*++argv, "r")) == NULL) {
                fprintf(stderr, "%s: can't open %s\n",  prog, *argv);
                exit(1);
            } else {
                filecopy(fp, stdout);
                fclose(fp);
            }
    if (ferror(stdout)) {
        fprintf(stderr, "%s: error writing stdout\n", prog);
        exit(2);
    }
    exit(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.7 行输入和行输出 【getline函数】

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

抱歉!评论已关闭.