File Handling in C with Examples (fopen, fread, fwrite, fseek)

by Himanshu Arora on July 9, 2012

As with any OS, file handling is a core concept in Linux. Any system programmer would learn it as one of his/her initial programming assignments. This aspect of programming involves system files.

Through file handling, one can perform operations like create, modify, delete etc on system files. Here in this article I try to bring in the very basic of file handling. Hope this article will clear the top layer of this multilayer aspect.

File handling functions

In this article, we will cover the following functions that are popularly used in file handling :

fopen()

FILE *fopen(const char *path, const char *mode);

The fopen() function is used to open a file and associates an I/O stream with it. This function takes two arguments. The first argument is a pointer to a string containing name of the file to be opened while the second argument is the mode in which the file is to be opened. The mode can be :

  • ‘r’    :  Open text file for reading. The stream is positioned at the beginning of the file.
  • ‘r+’ :  Open for reading and writing. The stream is positioned at the beginning of the file.
  • ‘w’   :  Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
  • ‘w+’ : Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
  • ‘a’    : Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
  • ‘a+’ : Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

The fopen() function returns a FILE stream pointer on success while it returns NULL in case of a failure.

fread() and fwrite()

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen function. These functions accept three arguments. The first argument is a pointer to buffer used for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’ bytes long.

In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write) is returned.

fseek()

int fseek(FILE *stream, long offset, int whence);

The fseek() function is used to set the file position indicator for the stream to a new position. This function accepts three arguments. The first argument is the FILE stream pointer returned by the fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The available values for whence are SEEK_SET, SEEK_CUR, or SEEK_END.  These three values (in order) depict the start of the file, the current position and the end of the file.

Upon success, this function returns 0, otherwise it returns -1.

fclose()

int fclose(FILE *fp);

The fclose() function first flushes the stream opened by fopen() and then closes the underlying descriptor. Upon successful completion this function returns 0 else end of file (eof) is returned. In case of failure, if the stream is accessed further then the behavior remains undefined.

The code

#include<stdio.h>
#include<string.h>

#define SIZE 1
#define NUMELEM 5

int main(void)
{
    FILE* fd = NULL;
    char buff[100];
    memset(buff,0,sizeof(buff));

    fd = fopen("test.txt","rw+");

    if(NULL == fd)
    {
        printf("\n fopen() Error!!!\n");
        return 1;
    }

    printf("\n File opened successfully through fopen()\n");

    if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))
    {
        printf("\n fread() failed\n");
        return 1;
    }

    printf("\n Some bytes successfully read through fread()\n");

    printf("\n The bytes read are [%s]\n",buff);

    if(0 != fseek(fd,11,SEEK_CUR))
    {
        printf("\n fseek() failed\n");
        return 1;
    }

    printf("\n fseek() successful\n");

    if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd))
    {
        printf("\n fwrite() failed\n");
        return 1;
    }

    printf("\n fwrite() successful, data written to text file\n");

    fclose(fd);

    printf("\n File stream closed through fclose()\n");

    return 0;
}

The code above assumes that you have a test file “test.txt” placed in the same location from where this executable will be run.

Initially the content in file is :

$ cat test.txt
hello everybody

Now, run the code :

$ ./fileHandling 

 File opened successfully through fopen()

 Some bytes successfully read through fread()

 The bytes read are [hello]

 fseek() successful

 fwrite() successful, data written to text file

 File stream closed through fclose()

Again check the contents of the file test.txt. As you see below, the content of the file was modified.

$ cat test.txt
hello everybody
hello

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 31 comments… read them below or add one }

1 Jalal Hajigholamali July 9, 2012 at 9:09 am

Hi,

Deeply, thanks a lot
very nice article and i sent it to my students in university

2 Marshall Neill July 9, 2012 at 10:24 am

This is not really reading a file, it reading an ITEM. A file contains items. So a Directory is more appropriately called a file and all items with in it, including other Directories are Items. I worked on the Pick System. That system READs and ITEM.
To access the file you would Open filename to filenamevariable. If the file doesn’t exist the Open statement fails and it is up to the programmer to resolve via error coding; e.g. Create the file.
When you want an item you READ item FROM filenamevariable THEN.
If the item doesn’t exist, then once again the programmer has to resolve error.
So in closing it would go something like this;
The id would be supplied by user or via a select list (another story altogether)
open “Invoices” to Invf then
read item from Invf, id else item=”"
do whatever you need to do with the item by referencing a specific attributes (fields)
When done
write item on invf, id
end
When the program ends the file is closed automatically.

Let the flames begin.. lol

3 Catalin July 10, 2012 at 11:05 am

I need a c++ file handling solution under linux , using gcc.
Thank’s . Regards.

4 r00tcrypt August 1, 2012 at 6:23 am

for good formatting, adding newline after calling the fwrite function
fprintf(fd,”\n”);

5 Karl August 18, 2012 at 3:52 am

Are you certain of the following:
“In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write) is returned.”

If gcc lib is used then fread returns the block count not the number of bytes read.
This also means that if EOF is reached that the partial block is dropped, not returned.

fread will only return the bytes read if the block size is 1, so:
blockRead = fread(blocks, 1, blockMax, file)

http://www.gnu.org/software/libc/manual/html_mono/libc.html#Block-Input_002fOutput

Or perhaps your using a different fread?

6 neha khade August 26, 2012 at 1:28 am

really thanxxx your article help me alott in my project work…..!!!!

7 rohini October 19, 2012 at 9:07 am

nice article

8 Peter October 29, 2012 at 3:43 am

There is no fwrite function to add the second line of text.

9 vaghela kamlesh babulal January 18, 2013 at 11:13 am

Thanks to all devloper who devlop this website , i like and i gane knowledge about file handling in c , it’s very helpful in my first mca sem c project. i agai say thanks………….
kamlesh

10 vijay sahu nitj March 9, 2013 at 2:09 am

//THIS PROGRAM WRITE RECORDS IN A FILE AND THEN READ IT RECORDS IN SORTED ORDER BY NAMES IN RECORD
//AND DISPLAY THEM ON SCREEN
#include
#include
#include
int main()
{
FILE *fw,*fr;
char opsn=’y';
char *p;
int count=0;
//for writing records into file
struct student
{
char name[20];
int age;
}s;

fw=fopen(“op.txt”,”w”);
while(opsn==’y')
{
count++;
printf(“Enter student name and age\n”);
scanf(“%s%d”,s.name,&s.age);
fprintf(fw,”%3s%3d\n”,s.name,s.age);
printf(“Wanna enter another record(y|n)\n”);
fflush(stdin);
opsn=getche();
}
fclose(fw);
//for reading records rom file
fr=fopen(“op.txt”,”r”);
struct st
{
char nm[20];
int ag;
}s2[count];

printf(“\nRecord from file is\n”);
int i=0,j;
char temp[20];
while(fscanf(fr,”%s%d”,s.name,&s.age)!=EOF)
{
strcpy(s2[i].nm,s.name);
s2[i].ag=s.age;
i++;
}
// for sorting records
for(i=0;i<count;i++)
{ for(j=i+1;j0)
{
strcpy(temp,s2[i].nm);
strcpy(s2[i].nm,s2[j].nm);
strcpy(s2[j].nm,temp);
}}}
//for displaying records
for(i=0;i<count;i++)
printf("\n%s\t\t%d",s2[i].nm,s2[i].ag);
fclose(fr);
}

11 joanna March 10, 2013 at 5:09 am

hi i have a question regarding c program.
how can i do this?
write a program that reads a file (file1) containing random strings. my program must be able to create another file (file2), to copy the contents of file1. my program should be able to alphabetically sort the contents of file2. my probplem is i dont know to sort the existing file. hope i can get some answer thank you.

12 vijay sahu nitj March 12, 2013 at 8:45 am

@joanna: you should try to sort file strings as normal strings.
sorting method is same for both but accessing method for strings is different.
try to understand in parts.

13 Anonymous April 3, 2013 at 7:03 am

write aprogram of updation in file

14 TWAGIRUMUKIZA Jean Paul April 25, 2013 at 7:31 am

I want you to show me the codes to display the bellow output (form of rectangle using stars in c file):

       *   *   *   *   *   *   *   * 
       *                             *
       *                             *
       *   *   *   *   *   *   *   *
15 kiran patel May 10, 2013 at 10:09 pm

how to design structure by using three dimentional vector?

16 Marshall May 12, 2013 at 6:30 pm

I come from a background in the Pick OS where we do a READ and get the whole item which is delineated by attribute marks char(254), value marks char(253) and sub-value marks char(252). What I am wondering how would a Pick READ, implemented in C I assume, would that be done?
I found that Pick is the only OS/DataBase management system to be capable of a READ of the nature I describe.
Just curious.

17 Falguni June 9, 2013 at 9:23 am

How can I end a file , while getting characters as input and wanna to save them?

18 Marshall Neill June 11, 2013 at 7:29 am

Marshall,
I have no idea how the Pick system is implemented. I worked at Pick Systems for years as a tech support person. I often worked with the programmers but never actually asked how the system was implemented. I would assume, and you know what that means, that it was written in C, C++ or … At Microdata, one of the Licensee’s of Pick, wrote it in Pick Assembly. Since Pick Systems, now Tiger Data I think, was porting to other platforms, AIX, PC, and hosting on Linux, C++ or C would see to be the likely candidates.
If I am wrong, please correct me.

19 IRRAMS July 2, 2013 at 4:20 am

tell me what is use of file handling concepts compare with structures

20 baby chuphal August 31, 2013 at 1:47 am

can u send me a c programe for updating the employee address with the help of file handling.

21 zaheen September 13, 2013 at 6:14 am

hey im very bad in programng..could u plz help me….thankk uu….

22 Apurva Popat September 16, 2013 at 12:47 pm

Thanks for the tutorial. Now I have a doubt that how to write to file in specific path?

23 Anonymous October 9, 2013 at 4:41 am

how can append a file to main file if filename is used in main file?

24 muruga October 21, 2013 at 2:22 am

how to over write a details using file handling

25 KHALID BIN ALI K January 3, 2014 at 12:28 am

thank you for your tutorial….

26 dev January 17, 2014 at 7:06 am

thanks for ur codding

27 sravan January 17, 2014 at 8:28 am

good explanation…..

28 Sagar gaikwad March 14, 2014 at 10:54 pm

what is use of file handling concepts ?

29 Krishna March 18, 2014 at 7:22 am

C language is very easy language.

30 @NS July 1, 2014 at 1:22 am
31 patrick July 15, 2014 at 7:08 am

this does not works dude

Leave a Comment

Previous post:

Next post: