Apue Chapter 5 習題答案

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. 




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章