【发布时间】: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", &initChoice) != 1) { fputs ("error: invalid integer input.\n", stderr); return 1; }。唯一对@有意义的问题987654330@是您在当前工作目录中没有写权限 - 验证打开并输出错误将有助于缩小问题。