Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Create Files

File Handling

In C, you can manage files by declaring a pointer of type FILE and utilizing the fopen() function for creating, opening, reading, and writing to files.

 FILE *fptr
fptr = fopen(filename, mode);

FILE is a data type used for file handling, and we typically create a pointer variable (fptr) of type FILE to work with it. This line is not crucial for now; it’s simply a prerequisite for file operations.

To open a file, utilize the fopen() function, which requires two parameters:

Parameter Description
filename The filename of the specific file you wish to open or create, such as filename.txt
mode

A single character indicating the desired file operation:

  • ‘w’: Writes to a file.
  • ‘a’: Appends new data to a file.
  • ‘r’: Reads from a file.

Create a File

To create a file, employ the ‘w’ mode within the fopen() function.

The ‘w’ mode is employed for writing to a file. If the file does not exist, it will be created:

Example

FILE *fptr;

// Create a file
fptr = fopen(“filename.txt”, “w”);

// Close the file
fclose(fptr); 

 

Note: If no specific path is provided, the file will be created in the same directory as your other C files.

On our computer, it appears as follows:

Image

Tip: To create the file in a particular directory, specify an absolute path.

fptr = fopen(“C:\directoryname\filename.txt”, “w”); 

 

Closing the file

Did you observe the fclose() function in the example provided earlier?

It’s responsible for closing the file once we’re finished using it.

It’s regarded as good practice because it ensures that:

  • Changes are accurately saved.
  • Other programs can access the file if necessary.
  • Unnecessary memory space is cleaned up.

In the forthcoming chapters, you’ll discover how to write data to a file and retrieve information from it.