Reputation: 19
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;
}
Upvotes: 1
Views: 729
Reputation: 7837
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.
Upvotes: 1