【问题标题】:How can I save the output of printf into a text file?如何将 printf 的输出保存到文本文件中?
【发布时间】:2021-10-16 12:32:27
【问题描述】:

在 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()
  • 我试过用 fprintf() 代替 printf() 但没用 -_- 可能我不知道如何在这里使用 fprintf()
  • 显示您尝试过的实际代码,您认为这些代码可以工作但没有。也就是说,提供complete minimal reproducible example
  • fclose(output_file);return 0; 之前更有意义(尽管流将在程序退出时关闭)显示cat output.dat 的输出
  • 您的代码真正唯一的问题是缺少验证fopen()(例如if (!output_file) { perror ("fopen-output_file"); return 1; },然后验证每个输入,例如if (scanf("%i", &amp;initChoice) != 1) { fputs ("error: invalid integer input.\n", stderr); return 1; }。唯一对@有意义的问题987654330@是您在当前工作目录中没有写权限 - 验证打开并输出错误将有助于缩小问题。

标签: c output


【解决方案1】:

当您想要保存到文件时,请使用 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);

【讨论】:

  • 请告诉初学者他们需要检查fopen()的返回值。
  • 警告:函数‘strerror’的隐式声明;您指的是 “perror” 吗? [-Wimplicit-function-declaration] 20 | fprintf(stderr, "打开文件写入失败:%s\n", strerror(errno)); | ^~~~~~~~ |错误输出
  • 如果你在 Linux 中并且在文件顶部包含 string.h,它应该可以工作。我还添加了一些错误检查(但不适用于 fprintf,尽管如果磁盘空间不足,它也可能会失败)
  • 添加 string.h 解决了编译问题。尽管正在创建输出文件,但我的输出文件仍然是空的 :( @sjoelund.se
  • 你确定你正在运行新编译的程序吗?您现在在问题中拥有的程序对我来说很好(在添加缺少的分号之后),包括文件中的预期输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多