Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn 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

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 12.5

bookWriting Data to Files

Swipe to show 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

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 1
some-alt