During the course of my program,
- I pass the output of an execv() to a file, for logging, (using the outCopy() function)
- and then print it back on screen to simulate stdout output. (using the printFile() function)
The 2 functions are:
void printFile(char *fileName)
{
char *fileContent=(char *)malloc(200*sizeof(char)); /* sufficiently large buffer */
if((filePtr=fopen(fileName,"r"))==NULL)
{
printf("Error opening %s: %s\n",fileName,strerror(errno));
if( (strcmp(fileName,"/tmp/command.log")==0) || (strcmp(fileName,"/tmp/output.log")==0) ){exitStatus=255;}
}
else
{
while(fscanf(filePtr,"%s",fileContent)!=EOF)
{
printf("%s",fileContent);
printf("%c",fgetc(filePtr));
}
fclose(filePtr);
}
}
void outCopy(char *fileName)
{
char *fileContent=(char *)malloc(200*sizeof(char)); /* sufficiently large buffer */
if( (filePtr=fopen(fileName,"r"))==NULL || (filePtr2=fopen("/tmp/output.log","a"))==NULL )
{
printf("Error opening files: %s\n",strerror(errno));
}
else
{
while(fscanf(filePtr,"%s",fileContent)!=EOF)
{
fprintf(filePtr2,"%s",fileContent);
fprintf(filePtr2,"%c",fgetc(filePtr));
}
fclose(filePtr);
fclose(filePtr2);
}
}
However, my neat little scheme gets disturbed for the output of the ls
command:
Expected output:
a.c c.c e.c
b.c d.c
Current output:
a.c
b.c
c.c
d.c
e.c
How can I change either or both of my functions to get the proper output?
(Please don't suggest using pipes or tees, or I will have to change a major portion of my exec() calling child)
Edit: Please note that both the outCopy()
& the printFile()
are run by the parent. Output has already been dup2()
ed to the required temp file by the child.