Skip to main content

File handling functions


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

Popular posts from this blog

C++ Program to find the sum, difference, product and quotient of two integers

#include <iostream.h> #include <conio.h> void main() {   clrscr();   int x = 10;   int y = 2;   int sum, difference, product, quotient;   sum = x + y;   difference = x - y;   product = x * y;   quotient = x / y;   cout << "The sum of " << x << " & " << y << " is " << sum << "." << endl;   cout << "The difference of " << x << " & " << "y <<  is " << difference << "." << endl;   cout << "The product of " << x << " & " << y << " is " << product << "." << endl;   cout << "The quotient of " << x << " & " << y << " is " << quotient << "." << endl;   getch(); }

Program of virtual piano

//////////////Tested And Created By C++/////////////////////////////// #include<stdio.h> #include<dos.h> #include<conio.h> #include<stdlib.h> #define SHOW 1 #define HIDE 2 union REGS input,output; class piano {  public:int BIGKEY,MIDKEY,back,border;     piano()//init constructor     {         BIGKEY=15;         MIDKEY=1;         back=7;         border=15;     } }color; void drawpiano(int x,int y); int check_xy(int x,int y); void BOX(int c,int r,int c1,int r1,int col); int initmouse(); void setupscreen(); void pointer(int on); void restrictmouse(int x1,int y1,int x2,int y2); void check_keys(int x,int y); void getmouse(int *button,int *x,int *y); float freq[7] = {130.81, 146.83, 164.81, 174.61,196, 220, 246.94 } ; int n=0,a=4,backcolor=2,exitcode=1; void showbar(int t) {  if(t>65) t=65;  if(t<1) t=1;  textcolor(15);  for(int q=0;q<=t;t++)  {     gotoxy(3+q,4);     cprintf("Û");  } } void main() {  int

Putimage function in c

putimage function outputs a bit image onto the screen. Declaration:- void putimage(int left, int top, void *ptr, int op); putimage puts the bit image previously saved with getimage back onto the screen, with the upper left corner of the image placed at (left, top). ptr points to the area in memory where the source image is stored. The op argument specifies a operator that controls how the color for each destination pixel on screen is computed, based on pixel already on screen and the corresponding source pixel in memory. c smiling face animation This animation using c draws a smiling face which appears at random position on screen. See output below the code, it will help you in understanding the code easily. C programming code #include<graphics.h> #include<conio.h> #include<stdlib.h>   main() { int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75; void *p;   initgraph(&gd,&gm,"C:\\TC\\BGI");   setcolor(YELLOW);