so learning operating systems course , right learning how system calls. ,i want copy input file openclose.in file called openclose.out. far here code
#include <cstdio> #include <unistd.h> #include <cstdlib> #include <sys/types.h> //needed open #include <sys/stat.h> //needed open #include <fcntl.h> //needed open #include <errno.h> //must use perror #include <grp.h> #include <pwd.h> using namespace std; int main (int argc, char *argv[]) { int infile; int outfile; int n_char=0; char buffer[32]; int fstat(int fildes, struct stat *buf); struct stat statbuf; struct group grp; struct passwd pwd; int err; int err2; if(argc != 3) { printf("usage: openclose <infile> <outfile> \n"); //return 1; exit(1); } infile=open(argv[1],o_rdonly); outfile=open(argv[2],o_rdwr); if (infile==-1) { printf(""); perror(argv[1]); exit(1); } //use read system call obtain 32 characters infile while( (n_char=read(infile, buffer, 32))!=0) { //display characters read n_char=write(argv[2],buffer,n_char); } err = fstat(infile, &statbuf); printf("the status of %d\n", argv[1]); printf("file size \t owner \t group id \t last modified \n %d \t \t %d \t %d \t \t %d \n",statbuf.st_size,statbuf.st_uid,stat,statbuf.st_gid,statbuf.st_mtime); return 0; }
but couldn't seem working, reason, don't know why not able see output file.
i running program terminal 2 arguments following
open(executable) inputfile1 inputfile2
your use of write()
not correct:
n_char=write(argv[2],buffer,n_char);
the first argument should file descriptor, use outfile
instead of file name in argv[2]
.
by way, should take habit of verifying if opening succeded, before trying file i/o. did infile
, outfile
Comments
Post a Comment