I made a C program that does what cat
command would do, but i ran into a problem. It works well now when adding multiple files as input. Now it doesn't show what was read at stdin
, when i don't put any file as a parameter. How can I fix this?
#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;
}
Use the source, Luke . The NetBSD cat.c implementation (see raw_args
function), starts by initializing a local variable to stdin. Then it enters the argv loop unconditionally. If *argv
is NULL, the local variable is still set, and it reads from stdin. Else it's overwritten for each argv element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.