File Handling in C — How to Open, Close, and Write to Files (2024)

/ #C
File Handling in C — How to Open, Close, and Write to Files (1)
freeCodeCamp
File Handling in C — How to Open, Close, and Write to Files (2)

If you’ve written the C helloworld program before, you already know basic file I/O in C:

/* A simple hello world in C. */#include <stdlib.h>// Import IO functions.#include <stdio.h>int main() { // This printf is where all the file IO magic happens! // How exciting! printf("Hello, world!\n"); return EXIT_SUCCESS;}

File handling is one of the most important parts of programming. In C, we use a structure pointer of a file type to declare a file:

FILE *fp;

C provides a number of build-in function to perform basic file operations:

  • fopen() - create a new file or open a existing file
  • fclose() - close a file
  • getc() - reads a character from a file
  • putc() - writes a character to a file
  • fscanf() - reads a set of data from a file
  • fprintf() - writes a set of data to a file
  • getw() - reads a integer from a file
  • putw() - writes a integer to a file
  • fseek() - set the position to desire point
  • ftell() - gives current position in the file
  • rewind() - set the position to the beginning point

Opening a file

The fopen() function is used to create a file or open an existing file:

fp = fopen(const char filename,const char mode);

There are many modes for opening a file:

  • r - open a file in read mode
  • w - opens or create a text file in write mode
  • a - opens a file in append mode
  • r+ - opens a file in both read and write mode
  • a+ - opens a file in both read and write mode
  • w+ - opens a file in both read and write mode

Here’s an example of reading data from a file and writing to it:

#include<stdio.h>#include<conio.h>main(){FILE *fp;char ch;fp = fopen("hello.txt", "w");printf("Enter data");while( (ch = getchar()) != EOF) { putc(ch,fp);}fclose(fp);fp = fopen("hello.txt", "r");while( (ch = getc(fp)! = EOF) printf("%c",ch);fclose(fp);}

Now you might be thinking, "This just prints text to the screen. How is this file IO?”

The answer isn’t obvious at first, and needs some understanding about the UNIX system. In a UNIX system, everything is treated as a file, meaning you can read from and write to it.

This means that your printer can be abstracted as a file since all you do with a printer is write with it. It is also useful to think of these files as streams, since as you’ll see later, you can redirect them with the shell.

So how does this relate to helloworld and file IO?

When you call printf, you are really just writing to a special file called stdout, short for standard output. stdout represents the standard output as decided by your shell, which is usually the terminal. This explains why it printed to your screen.

There are two other streams (i.e. files) that are available to you with effort, stdin and stderr. stdin represents the standard input, which your shell usually attaches to the keyboard. stderr represents the standard error output, which your shell usually attaches to the terminal.

Rudimentary File IO, or How I Learned to Lay Pipes

Enough theory, let’s get down to business by writing some code! The easiest way to write to a file is to redirect the output stream using the output redirect tool, >.

If you want to append, you can use >>:

# This will output to the screen..../helloworld# ...but this will write to a file!./helloworld > hello.txt

The contents of hello.txt will, not surprisingly, be

Hello, world!

Say we have another program called greet, similar to helloworld, that greets you with a given name:

#include <stdio.h>#include <stdlib.h>int main() { // Initialize an array to hold the name. char name[20]; // Read a string and save it to name. scanf("%s", name); // Print the greeting. printf("Hello, %s!", name); return EXIT_SUCCESS;}

Instead of reading from the keyboard, we can redirect stdin to read from a file using the < tool:

# Write a file containing a name.echo Kamala > name.txt# This will read the name from the file and print out the greeting to the screen../greet < name.txt# ==> Hello, Kamala!# If you wanted to also write the greeting to a file, you could do so using ">".

Note: these redirection operators are in bash and similar shells.

The Real Deal

The above methods only worked for the most basic of cases. If you wanted to do bigger and better things, you will probably want to work with files from within C instead of through the shell.

To accomplish this, you will use a function called fopen. This function takes two string parameters, the first being the file name and the second being the mode.

The mode are basically permissions, so r for read, w for write, a for append. You can also combine them, so rw would mean you could read and write to the file. There are more modes, but these are the most commonly used.

After you have a FILE pointer, you can use basically the same IO commands you would’ve used, except that you have to prefix them with f and the first argument will be the file pointer. For example, printf’s file version is fprintf.

Here’s a program called greetings that reads a from a file containing a list of names and write the greetings to another file:

#include <stdio.h>#include <stdlib.h>int main() { // Create file pointers. FILE *names = fopen("names.txt", "r"); FILE *greet = fopen("greet.txt", "w"); // Check that everything is OK. if (!names || !greet) { fprintf(stderr, "File opening failed!\n"); return EXIT_FAILURE; } // Greetings time! char name[20]; // Basically keep on reading untill there's nothing left. while (fscanf(names, "%s\n", name) > 0) { fprintf(greet, "Hello, %s!\n", name); } // When reached the end, print a message to the terminal to inform the user. if (feof(names)) { printf("Greetings are done!\n"); } return EXIT_SUCCESS;}

Suppose names.txt contains the following:

KamalaLoganCarol

Then after running greetings the file greet.txt will contain:

Hello, Kamala!Hello, Logan!Hello, Carol!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

File Handling in C — How to Open, Close, and Write to Files (3)
freeCodeCamp

Learn to code. Build projects. Earn certifications—All for free.

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTISEMENT

File Handling in C — How to Open, Close, and Write to Files (2024)

FAQs

File Handling in C — How to Open, Close, and Write to Files? ›

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 ).

How to create open, close, read, and write files in C? ›

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 ).

How to open a file and write into it in C? ›

File I/O in C
  1. Create a variable of type "FILE*".
  2. Open the file using the "fopen" function and assign the "file" to the variable.
  3. Check to make sure the file was successfully opened by checking to see if the variable == NULL. ...
  4. Use the fprintf or fscanf functions to write/read from the file.

How to open a file in both read and write mode in C? ›

For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.

What are the steps of file handling in C? ›

File Handling Function in C
  1. fopen() Opens a file.
  2. fprint() Prints an available file.
  3. fscan() Reads the data present in the file.
  4. fputc() Writes a character to the file.
  5. fgetc() Reads the character to the file.
  6. fseek() Sets the pointer to the intended file position.
  7. fclose() Closes a program file.
  8. fputw()
More items...
Aug 13, 2024

How to use fscanf() in C? ›

Syntax: int fscanf(FILE *ptr, const char *format, ...) fscanf reads from a file pointed by the FILE pointer (ptr), instead of reading from the input stream. Return Value: It returns zero or EOF, if unsuccessful.

How to perform open, read, write, and close into a file? ›

The four primary functions used for file handling in Python are:
  1. open() : Opens a file and returns a file object.
  2. read() : Reads data from a file.
  3. write() : Writes data to a file.
  4. close() : Closes the file, releasing its resources.
Aug 13, 2024

How to write text to a file in C? ›

To write a string of text into a file in C, you can use the following steps:
  1. Open the file using `fopen` with a mode of "w" for writing.
  2. Check if the file was opened successfully.
  3. Use `fprintf` or `fputs` to write the string into the file.
  4. Close the file using `fclose` when you're done.
Feb 14, 2022

Which function is used to close a file in C? ›

The fclose() function is used to close the file.

Which function is used to open a file in C? ›

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing, etc. along with various modes. If the file exists then the fopen() function opens the particular file else a new file is created.

How to read and then write to a file in C? ›

File Handling in C — How to Open, Close, and Write to Files
  1. fopen() - create a new file or open a existing file.
  2. fclose() - close a file.
  3. getc() - reads a character from a file.
  4. putc() - writes a character to a file.
  5. fscanf() - reads a set of data from a file.
  6. fprintf() - writes a set of data to a file.
More items...
Feb 1, 2020

How to read from one file and write to another in C? ›

Similar Reads
  1. Open file1.txt and file2.txt in read mode.
  2. Open file3.txt in write mode.
  3. Run a loop to one by one copy characters of file1.txt to file3.txt.
  4. Run a loop to one by one copy characters of file2.txt to file3.txt.
  5. Close all files.
Apr 19, 2024

How do you open a file for writing in C and create it if it doesn't exist? ›

The open() function in C is used to open the file for reading, writing, or both. It is also capable of creating the file if it does not exist. It is defined inside <unistd. h> header file and the flags that are passed as arguments are defined inside <fcntl.

How do you open and close a data file in C? ›

Function fopen() is used both to open or create a file, and fclose() is used to close an already opened file. File 'read' and 'write' operations can be performed after opening a file. The fputc() and fputs() functions are used to write characters and strings respectively in a file.

How do I open a file in C? ›

In C, you open a file using the fopen function, which takes two arguments: the name of the file and the mode you want to use. The mode is usually r to read from a file or w to write to a file. The mode supports other options too, but for this tutorial, just focus on reading and writing.

What are the 3 steps needed to process a file in C? ›

Declare a file pointer variable. Open a file using fopen() function. Process the file using the suitable function.

How to create a .C file? ›

An easy way to create a C file is to use Notepad. Type your C code into a Notepad file and then save the file with the . c extension. Type the filename with quotes, such as "filename.

How to generate .i file in gcc? ›

Using GCC to generate executable files from source code files requires preprocessing, compilation, assembly, and linking. Preprocessing: Preprocess the source program (such as a . c file) to generate an . i file.

How to open and read a text file in C? ›

In order to read from or write to simple text files, three steps are needed:
  1. Open the file using fopen.
  2. Read from the file using fscanf or write to the file using fprintf.
  3. Close the file using fclose.

What is EOF in C? ›

The End of the File (EOF) indicates the end of input. After we enter the text, if we press CTRL+Z, the text terminates i.e. it indicates the file reached end nothing to read.

Top Articles
Latest Posts
Recommended Articles
  • Animal Well Review | XboxAchievements.com
  • Trailer Kimi Machi Bus
  • Watch Only The Flower Knows Episode 15
  • Thirteen Official Merch
  • The Hero's Savior Volume 14
  • Descargar Crier 1080P
  • How Many Movies Are There In Snakes And Earrings (2008)
  • How Many Levels Are In Pro Mahjong Kiwame Iii
  • Can I insurance my TV for accidental damage?
  • Hamilton (2020) | Rotten Tomatoes
  • Significado del nombre Leslie – Significado de Nombres
  • Gohs Episode 19 Gogoanime
  • Kevin Bray Exposed
  • Review Of Love You Long Time (2023)
  • Lucifer and the Biscuit Hammer (Anime)
  • Epic Mickey: Rebrushed Release Date & Preorders
  • Baked Sweet Glasses 171
  • Titanomachy_(A_Collection_of_Threats_for_Scion_Second_Edition).pdf - PDFCOFFEE.COM
  • Densetsu No Quiz-Ou Ketteisen Free Download Ios
  • Choice 10 3/4&quot; x 14&quot; Insulated Foil Sandwich Wrap Sheets - 500/Pack
  • Aluminium NEE NEE sticker brievenbus – NEE NEE sticker – 5 JAAR GARANTIE | bol
  • Watch Demon Slayer: Kimetsu no Yaiba English Sub/Dub online Free on HiAnime.to
  • Tomijuu S1
  • Who Starred In The Movie Reborn As A Vending Machine, I Now Wander The Dungeon
  • Hirsutism. Excessive hair in females
  • No+baby+blisters+scam | New & Used Personal Care Items for Sale | NL Classifieds
  • Yuriy Popovich Sandwich
  • 17 Nissin Cup Noodles Flavors, Ranked Worst To Best - Tasting Table
  • Watch The Protector | Netflix Official Site
  • The Last Samurai Movie Review
  • When Does The New Celestial Crown Update Come Out
  • Broken Down Film Volume 1 Pdf
  • The 24 Best Products for Curly, Frizzy Hair
  • What Rating Is Finding Escobar's Millions
  • Master Axe: The Genesis of MysterX (Amiga)
  • When Is Season 5 Of Nenbutsu Monogatari: Shinran-Sama - Negai Coming Out
  • Is Duncanville On Crunchyroll
  • What Is an Erectile Dysfunction Pump?
  • What Genre Is お祭り野郎 魚河岸の兄弟分 (1976)
  • Read Jojorion Raw
  • Irene Dunne, Leading Star of '30s and '40s, Dies at 88 : Film: She pioneered in establishing contract rights. The actress was nominated for five Oscars.
  • 경기도 안산시 상록구 본오동 동산(주상복합) 아파트 단지 정보 | 아파트 특성, 편의시설, 가격 비교 가이드'
  • Ero Life Next Episode Date
  • The Ghost Conqueror American Cast
  • 6 best Korean dramas and movies starring new dad Lee Seung Gi
  • Marc Anthony Old Pictures
  • The Old Dark House Blu-Ray 1963 William Castle Indicator Series New + Sealed 📀 • £12.95
  • 45+ Sweet Pink Nail Design Ideas for a Manicure That Suits Exactly What You Need
  • The Christmas Cure (2017) 4K Download
  • Sonic Ng Ico
  • Guide to Using A Hydra Facial Machine: Step by Step - konmison
  • The Best LCD and UV Nail Dryers for Faster Manicures
  • Fureru Ondo Season 3 Episode 13
  • BBC - 7 songs you never knew were made by Nile Rodgers
  • Sun Zhongyang Poses
  • Reishi Mushroom 2500mg (365 Capsules) Heart, Immune, Stress, Anxiety, Memory • £25.19
  • The best hair dryers for 2024, tried and tested with expert advice from an A-list stylist
  • How Many Books Are In The World? (2024) - ISBNDB Blog
  • Specs To Run Dysmantle
  • Gyakuten Guilty Good Or Bad
  • The Cuckoo Clock (1950) Full Movie Google Drive
  • Clé magnétique bleu sur le forum Yôkai Watch 2 : Ganso - 29-04-2017 14:19:17
  • Aku Jati, Aku Asperger (2024) Ending
  • Monster Strike: Zoku Saishuu-Banashi - Pandora No Hako S2 Ep 6
  • Lol: Last One Laughing Sweden Movie Trailer
  • Glutamine (oral route)
  • Replicas (2018) English Actors
  • If You're Sick of Cracked Knuckles, I Found 11 Hand Soaps That Rival Your Lotion
  • Easy Anti Cheat Clash Royale
  • Miracle In Cell No. 7 (2013) Movie Synopsis
  • Scrolls Of Frolicking Animals And Humans Season 4 Ending
  • Despairing teen refugee found hanged in Libya detention centre
  • Your Freedom - How to tunnel through DNS
  • André Téchiné Haircut 2025
  • Eye Pads For Eyelash Extensions: Details, Costs, and Reviews
  • Contacts for Astigmatism: Lens Options & How to Choose – NVISION Eye Centers
  • Hand & Foot Treatment - Body Care | Ulta Beauty
  • Denis Martin-Laval Makeup Routine
  • Top 25 Best Romance Anime of All Time
  • Watch Elfen Lied English Sub/Dub online Free on HiAnime.to
  • How Many Episode In Lapis Lazuli No Oukan
  • Deep State Sells Out Their Own With A Money Laundering Operation, BRICS-Pay.com | Russian Mafia Duped, Sends Huge Amount of Weapons For War in Middle East | Rothschild Sells Israel On Religious War, the Final Battle | Last Day of Equinox Has SSP Fantasizi
  • Hachiue No Juunin Chapter 143
  • Dejig: Aqua World Randomizer
  • The 5 Most Sustainable Destinations To Visit In Europe, Ranked In New Report
  • Scandal In Vatican 2: The Swiss Guard (2024) Awards
  • fiX - A ParaBnormal Fairy Tale (Michael Golvach) » p.1 » All Books Online Free ?
  • Anime The Life Of Guskou Budori Watch
  • 6 Eco-Friendly Refillable Shampoo Bottles That Will Instantly Upgrade Your Shower Routine
  • Difference between CD, DVD, and Blu-ray discs - Know Computing
  • Whats Danmachi About
  • Voodoo Castle Backwards Compatible Xbox One
  • Hottest 1970's Television Crime Drama Actor
  • How Dream Horse (2021) Ends
  • Departed Dlc 2 Release Date
  • The World-Famous Punk Band That Was Almost Named "Warsaw"
  • The Dove (1968) The Movie
  • We Are Pretty Cure: Max Heart Anime Film
  • PM Studios brings Black Myth: Wukong Physical Edition to PS5
  • mixed nail
  • 0 5cm caviar beads nail jewels half round pearl gems diy
  • 24pcs french nail sticker
  • nail
  • y2k adhesive
  • black and white love abstract flower nail art decoration nail slider sexy
  • mold printing plates nail art stencil stamp tool
  • 1pc sea starfish shell conch3d acrylic nail mold nail decorations
  • steel nail cutter
  • lime 240 sandpaper gel
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5551

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.