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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.