-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathp1.c
More file actions
73 lines (66 loc) · 1.94 KB
/
p1.c
File metadata and controls
73 lines (66 loc) · 1.94 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <string.h>
#include "apue.h"
void pr_stdio(const char *, FILE *);
int is_unbuffered(FILE *);
int is_linebuffered(FILE *);
int buffer_size(FILE *);
void my_setbuf(FILE *restrict fp, char *restrict buf);
int main() {
FILE *fp = fopen("test", "w");
char buf[BUFSIZ];
pr_stdio("fp", fp);
my_setbuf(fp, NULL);
pr_stdio("fp", fp);
my_setbuf(fp, buf);
pr_stdio("fp", fp);
pr_stdio("stderr", stderr);
my_setbuf(stderr, buf);
pr_stdio("stderr", stderr);
pr_stdio("stdin", stdin);
my_setbuf(stdin, buf);
pr_stdio("stdin", stdin);
pr_stdio("stdout", stdout);
my_setbuf(stdout, buf);
pr_stdio("stdout", stdout);
return 0;
}
void my_setbuf(FILE *restrict fp, char *restrict buf) {
int len = BUFSIZ;
/* 如果 buf 为 NULL 或者为错误流的话,将缓冲类型改为无缓冲 */
if (buf == NULL || fp == stderr) {
if (setvbuf(fp, NULL, _IONBF, 0) != 0) {
err_sys("setvbuf _IONBF failure");
}
return;
}
int file = fileno(fp);
struct stat st;
if (fstat(file, &st) == -1) {
err_sys("fstat failure");
} else if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode) ||
S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
/* pipe , socket ,字符设备和块设备采用行缓冲 */
if (setvbuf(fp, buf, _IOLBF, len) != 0) {
err_sys("setvbuf _IOLBF failure");
}
} else {
if (setvbuf(fp, buf, _IOFBF, len) != 0) {
err_sys("setvbuf _IOFBF failure");
}
}
}
void pr_stdio(const char *name, FILE *fp) {
printf("stream = %s, ", name);
if (is_unbuffered(fp)) {
printf("unbuffered");
} else if (is_linebuffered(fp)) {
printf("line buffered");
} else {
printf("fully buffered");
}
printf(", buffer size = %d\n", buffer_size(fp));
}
int is_unbuffered(FILE *fp) { return (fp->_flags & _IO_UNBUFFERED); }
int is_linebuffered(FILE *fp) { return (fp->_flags & _IO_LINE_BUF); }
int buffer_size(FILE *fp) { return (fp->_IO_buf_end - fp->_IO_buf_base); }