C – File Operations, Open, Write and Close Files

RSS
FACEBOOK
FACEBOOK
PINTEREST
PINTEREST
LINKEDIN
INSTAGRAM

[rps-include post=6557]

While learning C programming language one of the most exciting part is writing and reading a file. Because this operations creates something on the operating system we can see which is different from other examples. In this tutorial we will look different aspects of file operations.

stdio.h Library

As  we know C provides different type of features with libraries. Input and output related features are provided by the library named stdio.h . In order to run related file operations we should include this library like below. We generally put include like to the start of the code file like below.

Opening File

The first step to work with a file is opening it. Files can be opened by using fopen function. fopen function generally gets the filename and mode parameters.

fopen  function returns a handler back where we use FILE type variable for this.

Below we will create a file pointer named fp and open file named test.txt with w+ write and read mode .

Closing File

In previous part we have opened a file with fopen function. But the code provided there is not an efficient code because file handler do not closed which means file is not closed. Not closing a file can create performance or write problems. So after our operation is completed we should close the file with fclose function.

LEARN MORE  How To Use PHP file() and readfile() Functions To Read PHP File?

and complete code will be like below.

Reading File

One of the fundamental step for file operation is reading a file. There are different ways and modes to read a file but in this step we simply read a line. We will put this in a while loop and read to the end of file. Because we will read file so we will use read mode while opening the file with fopen function.

We will provide the variable, str , we want to put grabbed string and the size to read which is 80 and the last one is the file pointer fp

And here fully working code where we use while to read line by line to the end of file. If end of file arrived the NULL value will be returned.

Writing File

In previous steps we have learned how to open and close file. But the ultimate goal is not opening and closing files. We generally read or write to file. There are different ways to write a file but in this tutorial we will simply put some line to the file. We will use fputs function by providing the string and file pointer like below.

LEARN MORE  Python, How To Print Without Newline or Space?

We can see the whole working example below.

[rps-include post=6557]

RSS
FACEBOOK
FACEBOOK
PINTEREST
PINTEREST
LINKEDIN
INSTAGRAM

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)