PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] How can I save the output of printf into a text file?

 August 16, 2022     c, output     No comments   

Issue

In Linux, I want to save a specific line into a text file. In the code, I have pointed out which line do I want to save. I have tried fopen() and fclose() but for some reasons it didn't work!

#include <stdio.h>
#include <stdlib.h>

float convertCelFahrenheit(float c)
{
    return ((c * 9.0 / 5.0) + 32.0);
}
int main()
{
    FILE *output_file
    output_file = fopen("output.dat", "w"); // write only
    while (1)
    {
        int initChoice;
        printf("Press 1 to convert into Fahrenheit\nPress 2 to exit\nProvide Input: ");
        scanf("%i", &initChoice);
        if (initChoice == 2)
        {
            break;
        }
        else if (initChoice == 1)
        {
            float celsius, fahrenheit;
            int endChoice;
            printf("Enter temperature in Celsius: ");
            scanf("%f", &celsius);
            fahrenheit = convertCelFahrenheit(celsius);
            printf("\n%.2f degree Celsius = %.2f degree Fahrenheit", celsius, fahrenheit);

            // I want to save the above line e.g. the printf output into a text file

            fprintf(output_file, "\n%.2f degree Celsius = %.2f degree Fahrenheit", celsius, fahrenheit);
            printf("\n\nDo you want to calculate for another value?\n[1 for yes and 0 for no]: ");
            scanf("%d", &endChoice);
            if (endChoice == 0)
            {
                break;
            }
        }
    }
    fclose(output_file);
    return 0;
}

Solution

Use fprintf instead of printf when you want to save to a file. printf(...) works like fprintf(stdout, ...).

#include <errno.h> /* errno */
#include <string.h> /* strerror */

FILE *fout = fopen("myFile.txt", "w"); // The "w" is important - you want to open the file for writing.
if (!fout) {
  fprintf(stderr, "Failed to open file for writing: %s\n", strerror(errno));
  return 1;
}
fprintf(fout, "\n%.2f degree Celsius = %.2f degree Fahrenheit", celsius, fahrenheit);
fclose(fout);


Answered By - sjoelund.se
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing