Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C Files


File Handling

In C, you can create, open, read, and write to files by declaring a pointer of type FILE, and use the fopen() function:

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

FILE is basically a data type, and we need to create a pointer variable to work with it (fptr). For now, this line is not important. It's just something you need when working with files.

To actually open a file, use the fopen() function, which takes two parameters:

Parameter Description
filename The name of the actual file you want to open (or create), like filename.txt
mode A single character, which represents what you want to do with the file (read, write or append):

w - Writes to a file
a - Appends new data to a file
r - Reads from a file


Create a File

To create a file, you can use the w mode inside the fopen() function.

The w mode is used to write to a file. However, if the file does not exist, it will create one for you:

Example

FILE *fptr;

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

// Close the file
fclose(fptr);

Note: The file is created in the same directory as your other C files, if nothing else is specified.

On our computer, it looks like this:

Run example »

Tip: If you want to create the file in a specific folder, just provide an absolute path (remember to use double backslashes to create a single backslash (\), like we specified in strings special characters):

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

Closing the file

Did you notice the fclose() function in our example above?

This will close the file when we are done with it.

It is considered as good practice, because it makes sure that:

  • Changes are saved properly
  • Other programs can use the file (if you want)
  • Clean up unnecessary memory space

In the next chapters, you will learn how to write content to a file and read from it.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.