I am trying a write a program that implements a bare bones POSIX cat
command. Although I have written the code and it behaves normally for the default (without paramaters) STDIN
, It doesn't work well for others. Can anyone help me with this. Here is the code:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFFSIZE 10240
#define MAX_FILES 127
int main(int argc, char *argv[])
{
int n,t,i;
char buf[BUFFSIZE];
char *myargv[MAX_FILES];
//aiparser(argv,myargv);
if (argc == 1) {
while(( n = read(STDIN_FILENO,buf,BUFFSIZE)) > 0) {
if (write(STDOUT_FILENO, buf ,n ) != n) {
perror("Write Error");
}
}
if ( n < 0 ) {
perror("Read Error");
}
}
else {
for ( i = 1; i < argc-1 ; i++) {
if (strcmp(argv[i],"-") != 0 ) {
t = open(argv[i],O_RDONLY);
}
else {
t = STDIN_FILENO;
}
while(( n = read(t,buf,BUFFSIZE)) > 0) {
if (write(STDOUT_FILENO, buf ,n ) != n) {
perror("Write Error");
}
}
if ( n < 0 ) {
perror("Read Error");
}
if (close(t) == -1) {
perror("Closing Error");
}
}
}
exit(0);
}
The problem is this:
i < argc-1
...which would mean you'd never actually execute the loop at all if you only pass a single argument.
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.