How to extend this code for doing "cat"

E

Elephant

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
int fd1, n;
char sl;

if (argc < 2) {
printf("Koristenje: vjezba4 <ime_datoteke>\n");
exit(0);
}

fd1=open(argv[1], O_RDONLY);
if (fd1 < 0) {
perror("open");
exit(-1);
}

while((n=read(fd1, &sl, 1)) > 0) {
write(STDOUT_FILENO, &sl, 1);
}

if (n == -1) {
perror("read");
}

close(fd1);
exit(0);
}How to extend this code for doing "cat"program starts by entering a file
name or more of them unless it s started with one filename it prints the
source of the file. If there is no filename in program the stdin will copy
the stdout
 
U

usenet

Elephant said:
How to extend this code for doing "cat"program starts by entering a file
name or more of them unless it s started with one filename it prints the
source of the file.

Check the value of argc; if no extra arguments are specified (argc==1), read
from the 'stdin' FILE. If argc is bigger then one, read file names one by
one from argv, open the files and handle them as you do now.
If there is no filename in program the stdin will copy the stdout

You probably mean 'stdin' instead of 'stdout' here
 
C

clayne

Elephant said:
if (argc < 2) {
printf("Koristenje: vjezba4 <ime_datoteke>\n");
exit(0);
}
How to extend this code for doing "cat"program starts by entering a file
name or more of them unless it s started with one filename it prints the
source of the file. If there is no filename in program the stdin will copy
the stdout

I typically just utilize the following (using stdio for this example,
but it shouldn't matter):

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
FILE *f_in;
char buf[256];

if (argc > 1 && *argv[1] != '-') {
if ((f_in = fopen(argv[1], "r")) == NULL)
exit(EXIT_FAILURE); /* or other handling */
} else
f_in = stdin;

while (fgets(buf, sizeof(buf), f_in) != NULL)
fprintf(stdout, "%s", buf);

exit(EXIT_SUCCESS); /* or simply return */
}


build02-sol8-x86:/tmp $ ./c
duh
duh
^D
build02-sol8-x86:/tmp $ ./c -
test
test
^D
build02-sol8-x86:/tmp $ echo test | ./c
test
build02-sol8-x86:/tmp $ echo test | ./c -
test
build02-sol8-x86:/tmp $ echo test_test >tmp
build02-sol8-x86:/tmp $ ./c tmp
test_test
build02-sol8-x86:/tmp $ cat tmp | ./c
test_test
build02-sol8-x86:/tmp $ ./c | ./c
1
2
^D
1
2
build02-sol8-x86:/tmp $
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,131
Latest member
IsiahLiebe
Top