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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Awesome!

Completion rate improved to 12.5

bookWriting Data to Files

Stryg for at vise menuen

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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1
some-alt