≡ Menu

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

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
Add your comment

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

Comments on this entry are closed.

  • Jalal Hajigholamali July 9, 2012, 9:09 am

    Hi,

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

  • Marshall Neill July 9, 2012, 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

  • Catalin July 10, 2012, 11:05 am

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

  • r00tcrypt August 1, 2012, 6:23 am

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

  • Karl August 18, 2012, 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?

  • neha khade August 26, 2012, 1:28 am

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

  • rohini October 19, 2012, 9:07 am

    nice article

  • Peter October 29, 2012, 3:43 am

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

  • vaghela kamlesh babulal January 18, 2013, 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

  • vijay sahu nitj March 9, 2013, 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);
    }

  • joanna March 10, 2013, 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.

  • vijay sahu nitj March 12, 2013, 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.

  • Anonymous April 3, 2013, 7:03 am

    write aprogram of updation in file

  • TWAGIRUMUKIZA Jean Paul April 25, 2013, 7:31 am

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

           *   *   *   *   *   *   *   * 
           *                             *
           *                             *
           *   *   *   *   *   *   *   *
    
  • kiran patel May 10, 2013, 10:09 pm

    how to design structure by using three dimentional vector?

  • Marshall May 12, 2013, 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.

  • Falguni June 9, 2013, 9:23 am

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

  • Marshall Neill June 11, 2013, 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.

  • IRRAMS July 2, 2013, 4:20 am

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

  • baby chuphal August 31, 2013, 1:47 am

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

  • zaheen September 13, 2013, 6:14 am

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

  • Apurva Popat September 16, 2013, 12:47 pm

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

  • Anonymous October 9, 2013, 4:41 am

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

  • muruga October 21, 2013, 2:22 am

    how to over write a details using file handling

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

    thank you for your tutorial….

  • dev January 17, 2014, 7:06 am

    thanks for ur codding

  • sravan January 17, 2014, 8:28 am

    good explanation…..

  • Sagar gaikwad March 14, 2014, 10:54 pm

    what is use of file handling concepts ?

  • Krishna March 18, 2014, 7:22 am

    C language is very easy language.

  • @NS July 1, 2014, 1:22 am
  • patrick July 15, 2014, 7:08 am

    this does not works dude

  • sharath October 14, 2014, 7:05 am

    I want to increment the content of one file by one whenever that file opens,
    I.e;just take an example as account number.whenever we are creating a new account program should return the account no, and also it should increment every accessing time

  • farshad December 8, 2014, 5:44 am

    Hi
    Thanks
    It’s exactly what i need. and It works well
    Thanks again 😉

  • akash199 December 20, 2014, 11:13 pm

    if there is a text file that already has data in it……can we reach to any part using fseek and just EDIT the file??
    if yes, how do we reach the point where we want to reach?

  • Patibra January 8, 2015, 2:35 pm

    vijay thank a lot man, but can you please explain the logarithmic logic of it? please dude

  • zed March 14, 2015, 8:02 am

    how can I update a or change a flight itinerary destination and origin using the flight id without destroying the other descriptions?

  • shazia April 3, 2015, 5:40 am

    please make it clear to me is it necessary in file processing is it necessary to through light on fgetch (), fgets(), fread (), fputc ()

  • shazia April 3, 2015, 5:40 am

    please make it clear to me

    in file processing is it necessary to through light on fgetch (), fgets(), fread (), fputc ()

  • vipin kumar May 25, 2015, 4:43 am

    please tell me ?
    what is file handling?

  • Trilok February 1, 2016, 1:20 am

    When to use fgets,fputs, over fread,fwrite, I’m confused with these.

  • Anonymous February 16, 2016, 6:15 am

    very help to us to do complex programs

  • jes February 18, 2016, 9:31 pm

    how can i add, view, and delete using file handling? or in turbo ?

  • kiran April 18, 2016, 10:15 pm

    plz tell mi..can we declare file handling as global file..

  • Vipasha Yadav December 10, 2016, 7:57 am

    What is recursion?

  • Vipasha Yadav December 10, 2016, 7:58 am

    File processing in C?

  • Vipasha Yadav December 10, 2016, 8:03 am

    Really very thanks! As always …. helping me making my project.

  • s.santha lakshmi February 24, 2017, 10:05 pm

    File handling concept