0
0
CHow-ToBeginner · 3 min read

How to Write to File in C: Simple Guide with Examples

To write to a file in C, use fopen to open the file in write mode, then use fprintf or fwrite to write data, and finally close the file with fclose. This sequence ensures your data is saved properly.
📐

Syntax

Here is the basic syntax to write to a file in C:

  • FILE *fopen(const char *filename, const char *mode); opens the file.
  • fprintf(FILE *stream, const char *format, ...); writes formatted text.
  • fwrite(const void *ptr, size_t size, size_t count, FILE *stream); writes raw bytes.
  • fclose(FILE *stream); closes the file to save changes.

The mode "w" means write mode, which creates or overwrites the file.

c
FILE *file = fopen("filename.txt", "w");
if (file != NULL) {
    fprintf(file, "Hello, world!\n");
    fclose(file);
}
💻

Example

This example opens a file named output.txt, writes a line of text, and closes the file. It shows how to check if the file opened successfully.

c
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    fprintf(file, "Writing this line to the file.\n");
    fclose(file);
    printf("File written successfully.\n");
    return 0;
}
Output
File written successfully.
⚠️

Common Pitfalls

Common mistakes when writing to files in C include:

  • Not checking if fopen returns NULL, which means the file couldn't be opened.
  • Forgetting to close the file with fclose, which can cause data loss.
  • Using the wrong mode (e.g., "r" for reading instead of "w" for writing).
  • Writing data without flushing or closing, so data may not be saved.
c
/* Wrong way: Not checking fopen and missing fclose */
FILE *file = fopen("file.txt", "w");
fprintf(file, "Hello");

/* Right way: Check fopen and close file */
FILE *file2 = fopen("file.txt", "w");
if (file2 != NULL) {
    fprintf(file2, "Hello");
    fclose(file2);
}
📊

Quick Reference

FunctionPurposeExample Usage
fopenOpen a fileFILE *f = fopen("file.txt", "w");
fprintfWrite formatted textfprintf(f, "Number: %d", 10);
fwriteWrite raw bytesfwrite(buffer, sizeof(char), size, f);
fcloseClose the filefclose(f);

Key Takeaways

Always open the file with fopen in write mode before writing.
Use fprintf or fwrite to write data to the file.
Check if fopen returns NULL to handle errors.
Close the file with fclose to save changes.
Writing without closing or flushing may cause data loss.