Writing Data to Files
When you want to save data from your program into a file, C provides several functions for writing, each suited for different data types and formats. Two of the most commonly used functions are fprintf and fwrite. The fprintf function is used to write formatted text to a file, much like how printf prints formatted output to the console. You can use it to write strings, numbers, or any formatted text. On the other hand, fwrite is designed for writing binary data, such as arrays or structures, directly from memory to a file without any formatting or conversion. This makes fwrite ideal for saving raw data efficiently, while fprintf is best when you need human-readable text output.
main.c
123456789101112131415#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { printf("Could not open file for writing.\n"); return 1; } fprintf(file, "Hello, world!\n"); fprintf(file, "The answer is: %d\n", 42); fclose(file); return 0; }
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 12.5
Writing Data to Files
Svep för att visa menyn
When you want to save data from your program into a file, C provides several functions for writing, each suited for different data types and formats. Two of the most commonly used functions are fprintf and fwrite. The fprintf function is used to write formatted text to a file, much like how printf prints formatted output to the console. You can use it to write strings, numbers, or any formatted text. On the other hand, fwrite is designed for writing binary data, such as arrays or structures, directly from memory to a file without any formatting or conversion. This makes fwrite ideal for saving raw data efficiently, while fprintf is best when you need human-readable text output.
main.c
123456789101112131415#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { printf("Could not open file for writing.\n"); return 1; } fprintf(file, "Hello, world!\n"); fprintf(file, "The answer is: %d\n", 42); fclose(file); return 0; }
Tack för dina kommentarer!