i have written the following program. The function of this prog is to read data from a file(source.c) and write into another file(dest.c) using pipes. I have just written a line in the source file.Im able to compile and run the program without errors. But the data is not written onto the other file(dest.c);
please help!!!!!!!!!!!!!!!!!!!!!!
Code:
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
int pfd[2],i=0,j=0;;
pid_t cpid;
char buf[20],ch,c;
FILE *fp1,*fp2;
fp1=fopen("source.c","r+");
if(fp1==NULL)
{
perror("Error opening source file\n");
}
while((ch=getc(fp1))!=EOF)
{
buf[i]=ch;
printf("i=%d ch=%c\n",i,ch);
i++;
}
buf[i] = '\0';
fclose(fp1);
if (pipe(pfd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0)
{ /* Child reads from pipe */
char arr;
close(pfd[1]); /* Close unused write end */
fp2=fopen("dest.c","w+");
if(fp2==NULL)
{
perror("Error opening dest file\n");
_exit(1);
}
printf("in client\n");
int i = 0;
while (read(pfd[0], &arr, 1) > 0)
{
i++;
printf("\n %c", arr);
putc((int)arr, fp2);
}
//read(pfd[0], &arr, 1);
printf("\n %c", arr);
printf("i = %d\n", i);
close(pfd[0]);
_exit(EXIT_SUCCESS);
}
else
{ /* Parent writes argv[1] to pipe */
j=0;
close(pfd[0]); /* Close unused read end */
write(pfd[1], buf, strlen(buf));
j++;
close(pfd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
fclose(fp2);
}