【问题标题】:Problems with C program that replicates `cat` command复制`cat`命令的C程序问题
【发布时间】:2020-07-28 06:57:21
【问题描述】:

我编写了一个 C 程序来执行 cat 命令会执行的操作,但我遇到了问题。现在添加多个文件作为输入时效果很好。现在它不显示在stdin 读取的内容,当我没有将任何文件作为参数时。我怎样才能解决这个问题?

#include<stdio.h>
#include<fcntl.h>
#include<stdarg.h>
#include<stdlib.h>
#include    "ourhdr.h"
#define BUFFSIZE    8192
int main(int argc,char *argv[])
{
    int fd;
    int n;
    char* index=argv[0];
    char buf[BUFFSIZE];
    if(argc ==1)
    {
        printf("<sintaxa> fisier1 fisier2....\n");
    }
    else
        while(--argc>0)
        {
            if((fd = open(*++argv,O_RDONLY)) == -1)
            {
                printf("%s: %s: No such file or directory\n",index,*argv);
            }
            else
            {
                while((n=read(fd,buf,BUFFSIZE)) > 0)
                    if(write(STDOUT_FILENO,buf,n) != n)
                    {
                        err_sys("write error");
                    }

                if(n<0)
                {
                    err_sys("read error");
                }
                close(fd);
            }
        }

    return 0;
}

【问题讨论】:

  • 如果没有文件名,或者文件名是 '-',则使用 fd = STDIN_FILENO 执行 while 循环。
  • @Rup 所以我应该修改第二个 while 而不是 stdout 使用 stdin 吗?
  • 不,您仍然想将数据写入标准输出:您只是想选择性地从标准输入读取它,而不是从您打开的文件中读取。我可能会重构循环并将if (n&lt;0) 签出到一个接受 fd 作为参数的不同函数中,以便您可以从几个不同的情况下调用它。

标签: c linux windows unix terminal


【解决方案1】:

Use the source, Luke。 NetBSD cat.c 实现(参见raw_args 函数)首先将一个局部变量初始化为标准输入。然后它无条件地进入 argv 循环。如果*argv 为NULL,则仍设置局部变量,并从标准输入读取。否则它会被每个 argv 元素覆盖。

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 2020-07-25
    相关资源
    最近更新 更多