现在我对每个人都有一个问题......我一直在盯着这几天进行修补和玩耍,但即便如此,我最终也会遇到大量错误......
我正在尝试做的是采取下面的程序并更改它,以便它需要一个可选的命令行参数infile.如果给出了infile,则将infile复制到标准输出,否则将标准输入复制到标准输出.
关于这一点的诀窍是解决方案必须使用原始复制循环(第9-11行)来处理这两种情况.人们只能插入代码,而不能更改任何现有代码.任何帮助都会很棒.谢谢.
/* $begin cpfile */
include "csapp.h"
int main(int argc, char **argv)
{
int n;
rio_t rio;
char buf[MAXLINE];
Rio_readinitb(&rio, STDIN_FILENO); //line 9
while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) //line 10
Rio_writen(STDOUT_FILENO, buf, n); //line 11
/* $end cpfile */
exit(0);
/* $begin cpfile */
}
/* $end cpfile */
Run Code Online (Sandbox Code Playgroud)
C程序通过两个参数得到命令行参数main(),传统上称为argc和argv(分别用于参数计数和参数向量).
参数不是"命名"任何东西,它们只是字符串.
您的解决方案可能如下所示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fileno;
/* ... your definitions should remain here, too */
if(argc > 1)
{
/* Assume first argument is filename, and open it. */
fileno = open(argv[1], O_RDONLY);
if(fileno < 0)
{
printf("Unable to open file, aborting\n");
return 1;
}
}
else
fileno = STDIN_FILENO;
/* ... your code goes here ... */
}
Run Code Online (Sandbox Code Playgroud)
那么你当然需要改变调用Rio_readinitb()以使用fileno变量作为文件描述符.
如果你真的无法改变那一行,无论出于何种原因......我猜你可以使用预处理器来使符号计算为新的变量名:
#undef STDIN_FILENO
#define STDIN_FILENO fileno
Run Code Online (Sandbox Code Playgroud)
这当然不是很漂亮,但应该有效.
确保你把那些预处理宏后的fileno = STDIN_FILENO;线.