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; }
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 12.5
Writing Data to Files
Desliza para mostrar el menú
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; }
¡Gracias por tus comentarios!