Reputation: 27
I am new to file operations like write/read in C. Is there a solution to write all printf() which is below, to my output text file? After execution I was not able to write all the lines to my text file.
for(i=0;i < n;i++)
if(i!=startnode)
{
outputFile = fopen(myOutputFile, "w");
printf("\nCOST of %d = %d", i, cost[i]);
printf("\nTRACE = %d", i);
j=i;
do
{
j=pred[j];
printf(" %d", j);
}
while(j!=startnode);
}
Upvotes: 0
Views: 3919
Reputation: 1970
Try this:
freopen(myOutputFile, "a+",stdout); //Redirect the standard output to file, "a+" - is for appending info if the file is has data before it is openned
for(i=0;i < n;i++)
{
if(i!=startnode)
{
printf("\nCOST of %d = %d", i, cost[i]);
printf("\nTRACE = %d", i);
j=i;
do{
j=pred[j];
printf(" %d", j);
}while(j!=startnode);
}
}
Upvotes: 0
Reputation: 2410
You can use fprintf(FILE * stream, const char * format, ... ) and pass the file handle to the function.
for(i=0;i < n;i++)
if(i!=startnode)
{
outputFile = fopen(myOutputFile, "a");
fprintf(outputFile,"\nCOST of %d = %d", i, cost[i]);
fprintf(outputFile,"\nTRACE = %d", i);
j=i;
do
{
j=pred[j];
fprintf(outputFile," %d", j);
}
while(j!=startnode);
fclose(outputFile);
}
According to your comment update the mode you are opening the file to: fopen("asdas","a")
Upvotes: 3
Reputation: 130
Try this:
outputFile = fopen(myOutputFile, "a");
for(i=0;i < n;i++)
if(i!=startnode)
{
fprintf(outputFile,"\nCOST of %d = %d", i, cost[i]);
fprintf(outputFile,"\nTRACE = %d", i);
j=i;
do
{
j=pred[j];
fprintf(outputFile," %d", j);
}
while(j!=startnode);
}
Upvotes: 0