Linux下CAT程序的C实现
Linux下CAT程序的C实现代码片段:
#include <stdio.h>
#include <fcntl.h>
#include <stdarg.h>
#define BUFSIZ 1024
void error(char *fmt, ...){
va_list args;
va_start(args, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
exit(1);
}
#include "syscalls.h"
main(int argc, char *argv[]){
char buf[BUFSIZ];
int n, f1;
if(argc == 1){
while((n = read(0, buf, BUFSIZ)) > 0){
write(1, buf, n);
}
}
else if(argc == 2){
if((f1 = open(argv[1], O_RDONLY, 0)) == -1){
error("cat: No such file or directory %s", argv[1]);
}else {
while((n = read(f1, buf, BUFSIZ)) > 0){
write(1, buf, n);
}
}
} else {
error("Wait for new version [email protected]");
}
}