Q5.1 Implement setbuf using setvbuf. 


Q5.2 Type in the program that copies a file using line-at-a-time I/O (fgets and fputs) from Figure 5.5, but use a MAXLINE of 4. What happens if you copy lines that exceed this length?

Explain what is happening.


正常情况下,在stdin 输入字符数小于4096时,我只显示一行 hello this is a test. 

但当我改为4自后,fgets每到4个字符就重新执行一次fgets.

正常情况下

$ ./fgets

hello

hello thi sis a test

zhangbo

hello thi sis a test

改过自后 MAXLINE1 = 4 可以看到输入两个字符时没有关系,fgets 运行一次。 

当我输入6个字符时它运行3次。 

$ ./fgets

ldsakfjlsdk

hello thi sis a test

hello thi sis a test

hello thi sis a test

hello thi sis a test

sfdfds

hello thi sis a test

hello thi sis a test

hello thi sis a test

sd

hello thi sis a test

sdf

hello thi sis a test

hello thi sis a test

sd

hello thi sis a test

源代码

$ cat fgets.c

#include "apue.h"

#define MAXLINE1 4

int

main (void)

{

  char buf[MAXLINE1];

  while ( fgets(buf, MAXLINE1, stdin) != NULL)    

    printf("hello thi sis a test\n");

    if( fputs(buf,  stdout) == EOF )

      err_sys("output error");

     if ( ferror(stdin))

        err_sys("input error");

    exit(0);

}

Q5.3 What does a return value of 0 from printf mean?

打印空的 printf(" ");

Q5.4 The following code works correctly on some machines, but not on others, What could be the problem?


#include <stdio.h>

int

main(void)

{

 char c;

 while (( c = getchar()) !== EOF)

          putchar(c);

}


Q5.5 How would you use the fsync function(Section 3.13) with a standard I/O stream?

对于标准I/O流如何使用fsync函数?

 The function fsync refers only to a single file, specified by the file descriptor fd, and waits for the disk writes to complete before returning, This function is used when an application, such as a database, needs to be sure that the modified blocks have been written to the disk. 

with fsync, the file's attributes are also updated synchronously. 

使用方法为:先调用fflush,然后在调用fsync,fsync所使用的参数有fileno函数获得。 

如果不调用fflush,所有的数据仍然在内存缓冲区中,此时调用fsync将没有任何效果。 


Q5.6 In the programs in Figures 1.7 and 1.10, the prompt that is printed does not contain a newline, and we don't call fflush. What causes the prompt to be output?

在交互式设备中,标准输入和标准输出都是行缓冲方式,每次调用fgets时标准输出自动冲洗。 


Q5.7 BSD-based systems provide a function called funopen that allows us to intercept read, write, seek, and close calls on a stream. Use this function to implement fmemopen for FreeBSD and Mac OS X.