如何将 printf 的输出保存到文本文件中?

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

在Linux中,我想将特定行保存到文本文件中。在代码中,我已经指出了我要保存哪一行。我试过 fopen() 和 fclose() 但由于某些原因它不起作用!

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

如果要保存到文件,请使用 fprintf 而不是 printfprintf(...) 的工作方式类似于 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);