CSAPP hw10

10.6

fd2 = 4

1
2
3
4
5
6
7
8
9
10
11
12
13
一个比较严谨的解答:
1.若成功打开“foo.txt”:

-->1.1若成功打开“baz.txt”: 输出“4\n”

-->1.2若未能成功打开“baz.txt”: 输出“-1\n”

2.若未能成功打开“foo.txt”:

-->2.1若成功打开“baz.txt”: 输出“3\n”

-->2.2若未能成功打开“baz.txt”: 输出“-1\n”
(不过课本上的练习题也没有考虑未能成功打开的情况)

10.7

1
2
3
4
5
6
7
8
9
10
11
12
#include "csapp.h"
int main()
{
int n;
rio_t rio;
char buf[MAXBUF];

Rio_readinitb(&rio, STDIN_FILENO);
while ((n = Rio_readnb(&rio, buf, MAXBUF)) > 0)
Rio_writen(STDOUT_FILENO, buf, n);
return 0;
}

10.8

怪怪的,没太懂这题是什么意思。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "csapp.h"
int main(int argc, char **argv)
{
int fd;
struct stat stat;
char *type,*readok;

fd = atoi(argv[1]);
Fstat(fd, &stat);
if (S_ISREG(stat.st_mode))
type = "regular";
else if(S_ISDIR(stat.st_mode))
type = "directory";
else
type = "other";
if ((stat.st_mode & S_IRUSR))
readok = "yes";
else
readok = "no";

printf("type: %s, read: %s\n", type, readok);
return 0;
}

10.9

参考 notes。

10.10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "csapp.h"

int main(int argc, char **argv)
{
int n;
rio_t rio;
char buf[MAXLINE];

if (argc == 2)
{
int fd = open(argv[1], O_RDONLY, 0);
dup2(fd, STDIN_FILENO);
close(fd);
}
Rio_readinitb(&rio, STDIN_FILENO);
while ((n = Rio_readnb(&rio, buf, MAXBUF)) > 0)
Rio_writen(STDOUT_FILENO, buf, n);
return 0;
}

CSAPP hw10
https://je3ter.github.io/2024/02/17/CSAPP/CSAPP hw10/
作者
Je3ter
发布于
2024年2月17日
许可协议