习题
5.1 用setvbuf实现setbuf
/*************************************************************************
> File Name: mysetbuf.c
> Author: Dennis
> Mail:wdennis051@gmail.com
> Created Time: 2017年09月22日 星期五 17时35分44秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <wait.h>
#include <fcntl.h>
#include "dennis.h"
void my_setbuf(FILE *restrict fp, char *restrict buf)
{
//if buf is NULL, then turn off buffer
if (buf == NULL){
if (setvbuf(fp, buf, _IONBF, void) < 0)
err_say("setvbuf");
}
else if (fp == stdin || fp == stdout){//if fp point to a tty device
if (setvbuf(fp, buf, _IOLBF, BUFSIZ) < 0)
err_say("setvbuf");
}
else {
if (setvbuf(fp, buf, _IOFBF, BUFSIZ) < 0)
err_say("setvbuf");
}
}
5.2 图5-5中的程序利用每次一行I/O(fgets 和 fputs函数)复制文件。若将程序中的MAXLINE改为4,当复制的行超过该最大值时会出现什么情况?对此进行解释。
复制的行超过最大值
5.3 printf返回0值表示什么
表示输出到stdout的是空字符串
int main(){
int result;
result = printf("");
printf("printf(hello) return %d\n",result);
return 0;
}
5.4 下面的代码在一些机器上运行正确,而在另外一些机器运行时出错,解释问题所在。
#include <stdio.h>
int
main(void)
{
char c;
while ((c = getchar()) != EOF)
putchar(c);
}
对char的解释不同导致了错误
有些编译器将char 当作有符号整数 -127 - 128 这种情况下,不会出错。
而有些编译器将char 当作无符号整数 0 - 255,由于EOF=-1D ,而char只能大于0,导致c 无法得到EOF,从而陷入死循环。
5.5 对标准I/O流如何使用fsync函数
fsync将住留在缓冲区高速缓存的数据块写入磁盘。而标准I/O函数将数据写入自己的缓冲区。要先调用fflush() 将数据冲刷到内核的缓冲区高速缓存,然后使用fileno函数将文件指针转换为file descriptor后,调用fsync函数
5.6 在图1-7和图1-10程序中,打印的提示信息没有包含换行符,程序也没有调用fflush函数,请解释输出提示信息的原因是什么?
每次调用fgets时都会自动冲刷缓冲区。