Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

File only print last line

while() {
    ...

    if (y == 1)
    {
        printf("success\n");
        FILE* fp2 = fopen("output.txt", "w");
        fprintf(fp2, "%d \n", a);
        fclose(fp2);
        break;
    }

}

If the condition is satisfied, I wanted to print the a value to file and success in program.

Many values of a that satisfies the condition was printed in program, but when I checked the output.txt file, there was only the value of the last a.

The reason for using break; is to break out of the loop when meets the condition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to print all the a‘s obtained through the loop.

How can I print all a‘s to a file?

>Solution :

There are two problems:

  1. First of all you actively break (stop) the loop once you have printed the first a. If you want to print all possible values of a calculated by the loop, you need to let the loop continue. Either by doing nothing or possibly by using continue to start from the top of the loop.

  2. Once you have fixed the above, you will open, close and reopen the file multiple times in the loop. Because you use the mode "w" each time you open the file it will be truncated and all its current contents will be lost.

    Instead open the file once before the loop, keep it open while inside the loop, and close it when the loop actually ends.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading