Dear Friend,
May be your file is not flushed, use the fflush(in),
I used "fprintf" instead of "write " function the file content is cpoied in to the second file.
sample code:
Code:
fprintf(in,"%s",buffer);
The main error is file is not flush you can try with the above line instead of write function.
write function also do this.
your didn't open the out file. I solved the problem see the following code.
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;
FILE *out;
in = fopen(infile, "r");
out = fopen(outfile, "w");
/* 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);
printf("%s\n",buffer);
//printf("%d\n",write(fd[WRITE_END], buffer, strlen(buffer)+1));
int val = fprintf(out,"%s",buffer);
printf("===%d\n",val);
fflush(in);
}
/* 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]);
}
}
}
Thank you.