As part of an assignment we were given code to copy a text input file into an output file. Parts of it were missing and I think I'm really close to solving the problem, but I seem to have run into an issue where either words or missing or it prints double versions into the output file which are missing a few letters.
I suspect it might have to do with it reading from the pipe incorrectly or that I open or closed the pipe in the wrong places but I can't seem to nail it down.
Here's my code:
Any assistance would be greatly appreciated I get the feeling at this point it's a minor mistake but I've been staring at it for hours.Code:#include <sys/types.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define BUFFER_SIZE 80 #define READ_END 0 #define WRITE_END 1 int main(int argc, char *argv[]) { /* argc must be 3 to ensure the correct usage */ if (argc != 3) { printf("The usage of this program is:\n"); printf("FileCopy input.txt copy.txt\n"); return 1; } else { /* initialize the pipe and fork variables */ int fd[2]; pid_t pid; /* argv[0] is the program name, argv[1] and argv[2] are the file names */ char *infile = argv[1]; char *outfile = argv[2]; /* create a pipe */ if (pipe(fd) == -1) { fprintf(stderr, "Pipe failed"); return 1; } /* fork */ pid = fork(); /* if pid < 0 there is an error */ if (pid < 0) { fprintf(stderr, "Fork error"); return 1; } /* parent code */ if (pid > 0) { /* close the unused end of the pipe */ close(fd[READ_END]); /* make a buffer to store input file information */ //char buffer[BUFFER_SIZE]; /* open input file */ FILE *in; in = fopen(infile, "r"); /* make sure it's not null */ if (in == NULL) { fprintf(stderr, "Error opening file %s\n", infile); return 1; } /* read from the file into the pipe thru the buffer */ while (! feof(in)) { char buffer[BUFFER_SIZE]; fgets(buffer, BUFFER_SIZE, in); write(fd[WRITE_END], buffer, strlen(buffer)+1); } /* close the input file */ fclose(in); /* close the pipe */ close(fd[WRITE_END]); } /* child process has pid == 0 */ else { /* create a buffer to read from the pipe and store into the out file */ //char buffer[BUFFER_SIZE]; /* close the unused end of the pipe */ close(fd[WRITE_END]); /* initialize the output file */ FILE *out; /* w+ means open a file for writing and create it if it doesn't exist */ out = fopen(outfile, "w+"); /* read from the pipe to the buffer */ //read(fd[READ_END], buffer, BUFFER_SIZE); /* write from the buffer to the file */ //fprintf(out, "%s", buffer); while(1) { char buffer[BUFFER_SIZE]; if (read(fd[READ_END], buffer, BUFFER_SIZE) != 0) fprintf(out,"%s",buffer); else break; } /* close the file and the pipe */ fclose(out); close(fd[READ_END]); } } }



LinkBack URL
About LinkBacks


