Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Writing Data to Files | Reading and Writing Data
C File Handling Basics

bookWriting 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

main.c

copy
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; }
question mark

Which function is best for writing formatted text to a file?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 1

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Awesome!

Completion rate improved to 12.5

bookWriting Data to Files

Glissez pour afficher le menu

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

main.c

copy
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; }
question mark

Which function is best for writing formatted text to a file?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 1
some-alt