FPRINTF()
this function takes an output from the program and saves it in a text file on the disk
SYNTAX
FILE *file = fopen("output.txt", "w");
fprintf(file, "Writing plain text using fprintf only.\n");
* the "w" mode creates the file if it doesn't exist and overwrites it if it does
* the fprintf writes formatted text to the file.
USAGE:
#include <stdio.h>
void run_main_program() {
// Step 1: Open file in write mode
FILE *file = fopen("/home/chef/workspace/help.txt", "w");
// Step 2: Check if file opened successfully
if (file == NULL) {
printf("Error opening help.txt\n");
}
else{
// Step 3: Write 3 lines using fprintf
fprintf(file, "Line 1: Use --help to show options.\n");
fprintf(file, "Line 2: Use --version to check version.\n");
fprintf(file, "Line 3: Use --exit to quit the program.\n");
// Step 4: Close the file
fclose(file);
}
}
int main() {
run_main_program();
return 0;
}
USAGE:
#include <stdio.h>
void run_main_program() {
// Step 1 - Open file in write mode
FILE* file = fopen("/home/chef/workspace/quotes.txt", "w");
// Step 2 - Check if file opened successfully
if (file == NULL) {
printf("Error opening quotes.txt\n");
}
else{
char* quotes[5] = {
"Stay positive.",
"Keep learning.",
"Believe in yourself.",
"Never give up.",
"Code with confidence."
};
// Step 3 - Use loop to write above quotes
for (int i = 0; i < 5; i++){
fprintf(file, "Quote %d: %s\n", i + 1, quotes[i]);
}
// Step 4 - Close the file
fclose(file);
}
}
//Main
int main() {
run_main_program();
return 0;
}
Last updated