DevAcademia
C++C#CPythonJava
  • C Basics

  • Introduction to C
  • Getting Started with C
  • C Syntax
  • C Output
  • C Comments
  • C Variables
  • C Data Types
  • C Constants
  • C Operators
  • C Booleans
  • C If...Else Statements
  • C Switch Statement
  • C While Loops
  • C For Loops
  • C Break and Continue
  • C Strings
  • C User Input
  • C Memory Address
  • C Pointers
  • C Files
  • C Functions

  • C Functions
  • C Function Parameters
  • C Scope
  • C Function Declaration
  • C Recursion
  • C Math Functions
  • C Structures

  • C Structures
  • C Structs & Pointers
  • C Unions
  • C Enums

  • C Enums
  • C Memory

  • C Allocate Memory
  • C Access Memory
  • C Reallocate Memory
  • C Deallocate Memory
  • C Structs and Memory
  • C Memory Example
  • C Quiz

  • C Quiz
  • C Basics

  • Introduction to C
  • Getting Started with C
  • C Syntax
  • C Output
  • C Comments
  • C Variables
  • C Data Types
  • C Constants
  • C Operators
  • C Booleans
  • C If...Else Statements
  • C Switch Statement
  • C While Loops
  • C For Loops
  • C Break and Continue
  • C Strings
  • C User Input
  • C Memory Address
  • C Pointers
  • C Files
  • C Functions

  • C Functions
  • C Function Parameters
  • C Scope
  • C Function Declaration
  • C Recursion
  • C Math Functions
  • C Structures

  • C Structures
  • C Structs & Pointers
  • C Unions
  • C Enums

  • C Enums
  • C Memory

  • C Allocate Memory
  • C Access Memory
  • C Reallocate Memory
  • C Deallocate Memory
  • C Structs and Memory
  • C Memory Example
  • C Quiz

  • C Quiz

Loading C tutorial…

Loading content
C BasicsTopic 45 of 64
←PreviousPrevNextNext→

C Create Files

Introduction to File Handling in C

File handling is a crucial aspect of programming that allows you to store data persistently on storage devices. In C, file operations are performed using functions from the stdio.h header file, which provides a standardized way to work with files across different platforms.

File handling enables programs to:

- Store data permanently beyond program execution

- Read configuration files and data inputs

- Create logs and output reports

- Exchange data between different programs

File Streams and FILE Pointer

In C, files are accessed through file streams. A file stream is an abstraction that represents a connection between your program and a file. The FILE structure (defined in stdio.h) contains information about the file and its current state.

Key concepts:

- FILE pointer: A pointer to a FILE structure that represents an open file

- Stream: A sequential flow of bytes between program and file

- Buffer: Temporary storage area that improves I/O efficiency

Opening Files with fopen()

The fopen() function opens a file and returns a FILE pointer. It takes two parameters:

- filename: The name of the file to open (including path if needed)

- mode: Specifies how the file should be opened

Example
FILE *fopen(const char *filename, const char *mode);
ℹ️ Note: Always check if fopen() returns NULL, which indicates the file couldn't be opened (use perror to see the reason).

File Opening Modes

ℹ️ Note: For update modes (r+, w+, a+), when switching between reading and writing, call fflush() or fseek() (or rewind()) first to avoid undefined behavior. On systems that distinguish text vs binary, append 'b' to the mode for binary files (e.g., "rb", "wb").
ModeDescriptionFile Position
"r"Open for reading (file must exist)Beginning
"w"Open for writing (creates or truncates)Beginning
"a"Open for appending (creates if doesn't exist)End
"r+"Open for reading and writing (file must exist)Beginning
"w+"Open for reading and writing (creates or truncates)Beginning
"a+"Open for reading and appending (creates if doesn't exist)End for writing, beginning for reading

Basic File Creation Example

⚠️ Warning: Using "w" mode will overwrite existing files without warning. Be careful when using this mode.
Example
#include <stdio.h>

int main(void) {
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        perror("fopen");
        return 1;
    }
    printf("File created successfully.\n");
    if (fclose(file) != 0) {
        perror("fclose");
        return 1;
    }
    return 0;
}
Output
File created successfully.

Writing to a New File

After creating a file, write data using fprintf(), fputs(), or fwrite() depending on your needs.

Example
#include <stdio.h>

int main(void) {
    FILE *file = fopen("report.txt", "w");
    if (!file) { perror("fopen"); return 1; }

    fprintf(file, "Name,Score\n");
    fprintf(file, "Alice,95\n");
    fputs("Bob,88\n", file);

    if (fclose(file) != 0) { perror("fclose"); return 1; }
    printf("Wrote report.txt\n");
    return 0;
}
Output
Wrote report.txt

Checking File Existence Before Creation

Example
#include <stdio.h>

int main(void) {
    char filename[100];
    printf("Enter filename to create: ");
    if (scanf("%99s", filename) != 1) {
        printf("Input error.\n");
        return 1;
    }

    FILE *file = fopen(filename, "rb"); // check existence (binary read)
    if (file != NULL) {
        fclose(file);
        printf("File already exists. Overwrite? (y/n): ");
        char choice;
        if (scanf(" %c", &choice) != 1 || (choice != 'y' && choice != 'Y')) {
            printf("File creation cancelled.\n");
            return 0;
        }
    }

    file = fopen(filename, "wb"); // create/truncate in binary
    if (file == NULL) { perror("fopen"); return 1; }
    printf("File '%s' created successfully.\n", filename);
    if (fclose(file) != 0) { perror("fclose"); return 1; }
    return 0;
}
ℹ️ Note: This example checks if a file exists before creating it and asks for confirmation to overwrite. On platforms that support exclusive create (e.g., mode "wx"), prefer it to avoid race conditions.

Binary vs Text Files

C distinguishes between text files and binary files:

- Text files: Store data as human-readable characters. Use modes like "r", "w", "a" (or with 't' on some systems).

- Binary files: Store data in raw binary format. Use modes like "rb", "wb", "ab".

The main difference is how newlines are handled and whether character translation occurs on the host platform.

Example
#include <stdio.h>

int main(void) {
    FILE *textFile = fopen("textfile.txt", "w");
    FILE *binaryFile = fopen("binaryfile.bin", "wb");

    if (textFile) { fputs("Line 1\nLine 2\n", textFile); }
    if (binaryFile) {
        unsigned char data[3] = {0xDE, 0xAD, 0xBE};
        fwrite(data, 1, sizeof data, binaryFile);
    }

    if (textFile && fclose(textFile) != 0) { perror("fclose text"); }
    if (binaryFile && fclose(binaryFile) != 0) { perror("fclose bin"); }

    if (textFile && binaryFile)
        printf("Both text and binary files created successfully.\n");
    else
        printf("Error creating one or more files.\n");

    return 0;
}
Output
Both text and binary files created successfully.
Test your knowledge: C Create Files
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C BasicsTopic 45 of 64
←PreviousPrevNextNext→