0

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);
    }
Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51
xxxx
  • 27
  • 2
  • 8

3 Answers3

3

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);
    }

Edit according to your comment:

According to your comment update the mode you are opening the file to: fopen("asdas","a")

ckruczek
  • 2,361
  • 2
  • 20
  • 23
  • Yes I tried but it only prints the last calculation to my file. I need all the i and cost[i] values in my file. also j value in do/while statement. – xxxx Mar 31 '16 at 10:49
  • Appending to the file should solve the problem. Everything else is unknown in your question. You should update your question accordingly. – ckruczek Mar 31 '16 at 10:55
  • thanks @ckruczek it worked. But I need something to clear my file. Because when I run again it always over writes and makes complex data inside of my file. – xxxx Mar 31 '16 at 11:15
  • This has been answered alot. [Here](http://stackoverflow.com/questions/4815251/how-do-i-clear-the-whole-contents-of-a-file-in-c) for example. – ckruczek Mar 31 '16 at 11:17
0

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);
    }
0

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);
    }
}
Shafi
  • 1,850
  • 3
  • 22
  • 44