Skip to main content

Opening and Closing a File in C programming


        While working with stream-oriented file, we need buffer area where information is stored temporarily in the course of transferring data between computer memory and data file. The buffer area is established as
             FILE * ptr_varibale;
          Where FILE is a special structure type that establishes the buffer area and ptr_variable is a pointer variable that indicates the beginning address of the buffer area. The special structure FILE is defined within header file stdio.h.

A data file must be opened before it can be created or processed. This is done by following syntax
         ptr_variable=fopen(file_name, file_mode);
This associate file name with the buffer area and specifies how the data file will be utilized (File opening mode). The function fopen() returns a pointer to the beginning of the buffer area associated with the file. A NULL value is returned if the file can be opened due to some reason. After opening a file, we can process data files as requirement. Finally, data file must be closed at the program. This is done using other library function fclose() as below
            fclose(ptr_variable);
        
File opening modes:
 The file opening mode specifies that how the data file is utilized while opening i.e. as read only or write only or read/write file. There are mainly six modes. They are illustrated as followings:

                          i.      “r” (i.e. read):
                      This opens an existing file for reading only. It file searches specified file. If file exists, it loads into memory and sets up a pointer which points to the first character in it. If file does not exist, it returns NULL. The possible operation is only- reading from the file

                        ii.      “w” (i.e. write):
               This mode of file opens a file for writing only. It searches specified file. If file already exist, the contents are overwritten. If file does not exist, a new file is created. It returns NULL, if it is unable to open the file. The possible operation is only- writing to the file.

                      iii.      “a” (i.e. append):
                  It opens an existing file for appending (i.e. adding new information at the end of   file). It searches specified file. If specified file exists, loads into memory and set up a pointer that points to the last character in it. If the file does not exist, a new file is created. It returns NULL if unable to open the file. The possible operation is –adding new contents at the end of file.

                      iv.      “r+” (i.e. read + write):
                 It opens existing file for reading and writing. It searches the specified file. If the file exists, loads it into memory and set up a pointer which points to the first character in it. Again, it returns NULL if file doesn’t exist. The possible operations are- reading existing contents, writing new contents, modifying existing contents of the file.

                        v.      “w+” (i.e. write + read):
                    It opens file for reading and writing. If the specified file exists, its contents are destroyed. If file doesn’t exist, the new file is created. It return NULL if unable to open file. The possible operations are- writing new contents, reading them back and modifying existing contents of the file.

                      vi.      “a+” (i.e. append+ read):
                   It opens an existing file for both reading and appending. A new file will be created if specified file doesn’t exist. The possible operations are- reading existing contents, appending new contents to end of file but it can not modify existing content.

The library functions related to reading and writing to a file
                i.      fgetc()
                 It is used to read a character from a file. Its syntax is
                 char_variable=fgetc(file_ptr_variable);

              ii.      fputc()
                It is used to write a character to a file. Its syntax is
                fputc(character or char_variable, file_ptr_variable);

            iii.      fgets()
                 It is used to read string from file. Its syntax is
                fgets(string_variable, int_value or int_variable, file_ptr_variable);
                    Here int_value or int_variable denotes the number of character in a string.


            iv.      fputs()
               It is used to write a string to a file. Its syntax is
                  fputs(string_variable, file_ptr_variable);

              v.      fprintf()
                  This function is formatted output function which is used to write some integer       
                       or float or char or string to a file. Its syntax is
               fprintf(file_ptr_variable, “control_string”, list_variables);

            vi.      fscanf()
             This function is formatted input function which is used to read some integer or          
                    float or char or string from a file. Its syntax is
                  fscanf(file_ptr_variable, “control_string”, &list_variables);


Example 1:
    Create a file named test.txt and write some text “Wel come to Acme” at the file.
void main()
  {
  FILE *fptr;
  clrscr();
  fptr=fopen("test.txt","w");
  if(fptr==NULL)
     {
     printf("\nFile can not be created");
     exit();
     }
  fputs("Wel come to Acme",fptr);
  fclose(fptr);
   }

Example 2:
  Write a program to open the file created in example 1, read its content and display.
void main()
  {
  FILE *fptr;
   char s[100];
    clrscr();
  fptr=fopen("test.txt","r");
  if(fptr==NULL)
     {
     printf("\nFile can not be opened");
     exit();
     }
  fgets(s,100,fptr);
  printf("\nFrom File\n%s",s);
  fclose(fptr);
 getch();
  }




Example 3:
  Create a program which asks file name from user and create it to write certain lines of text. It should write until the user hits enter at the beginning of line.
void main()
  {
  FILE *fptr;
  char s[200],fileName[20];
  clrscr();
  printf("\nEnter file name\n");
  gets(fileName);
  fptr=fopen(fileName,"w");
  if(fptr==NULL)
     {
     printf("\nFile can not be created");
     exit();
     }
   while(strlen(gets(s))!=0)
    {
     fputs(s,fptr);
    fputs("\n",fptr);
     }
  fclose(fptr);
   }

Example 4:
   Write a program to create file named test.txt and write some text to it. Write texts character by character using fputc() function. It should write until user hits enter key. Again, read its contents and display.

void main()
  {
  FILE *fptr;
  char c;
  clrscr();
  fptr=fopen("test.txt","w+");
  if(fptr==NULL)
     {
     printf("\nFile can not be created");
              }
    printf("Enter Text\n");
   while((c=getchar())!='\n')
       {
       fputc(c,fptr);
       }
     rewind(fptr);  /*set file pointer at initial position*/
     printf("\nThe Text From File\n");
   while((c=fgetc(fptr))!=EOF)
     {
     putchar(c);
     }
   fclose(fptr);
  getch();
  }

Example 5:
   Write a program to append some text to a certain file. Take file name from user.
void main()
  {
  FILE *fptr;
  char s[100],fileName[20];
  clrscr();
  printf("\nEnter file name at which u want to append\n");
  gets(fileName);
  fptr=fopen(fileName,"a");
  if(fptr==NULL)
     {
     printf("\nFile can not be created or opened");
              }
    printf("Enter Text to be appended\n");
   while((c=getchar())!='\n')
       {
       fputc(c,fptr);
       }
     fclose(fptr);
     getch();
  }


Example 6
  Create a program to create a data file and writes the natural number 1 to 20 and then read the numbers from file to display as twice of the stored numbers.
void main()
  {
  FILE *fptr;
  int i,numFromFile;
  clrscr();
  fptr=fopen("test1.txt","w");
  if(fptr==NULL)
     {
     printf("\nFile can not be created");
     exit();
     }
  for(i=1;i<=20;i++)
     {
     fprintf(fptr,"\n%d",i);
     }
   fclose(fptr);
  fptr=fopen("test1.txt","r");
  printf("\nThe output from File\n");
 for(i=1;i<=20;i++)
    {
    fscanf(fptr,"%d",&numFromFile);
    numFromFile=2*numFromFile;
    printf("\t%d",numFromFile);
    }

  fclose(fptr);
  getch();
  }

Example 7:
   Write a program that opens a file and copies all its content to another file. Take source and destination file from user.
void main()
  {
  FILE *fptrSource,*fptrDest;
  char ch,sourceF[20],destF[20];

  clrscr();
  printf("\nEnter Source File name\t");
  gets(sourceF);
  printf("\nEnter Destination File\n");
  gets(destF);
  fptrSource=fopen(sourceF,"r");
  if(fptrSource==NULL)
     {
     printf("\nFile can not be opened");
     exit();
     }
  fptrDest=fopen(destF,"w");
  if(fptrDest==NULL)
    {
    printf("\nDestination File can not be created\n");
    exit();
    }
    while((ch=fgetc(fptrSource))!=EOF)
       {
       fputc(ch,fptrDest);
       }
  fclose(fptrSource);
  fclose(fptrDest);
  getch();

   }

Comments

Popular posts from this blog

Difference between Binary mode and Text Mode in C programming

There are mainly three difference between binary and text mode. They are as follow.               i.       In text mode, a special character EOF whose ASCII value is 26 is inserted after the last character in the file to mark the end of file. But, there is no such special character present in the binary mode. The binary mode files keep track of the end of file from the number of characters present in the directory entry of the file.             ii.       In text mode of file, text and numbers are stored as one character per byte. For example, the number 1234 occupies two bytes in memory but it occupies 4 bytes (one byte per character) in the file. But, in binary mode, the number occupies the number of bytes as it occupies in the memory. Thus,  the above number occupies two bytes in file also in the case o...

Passing arrays to functions in C programming

Like any other variables, we can also pass entire array to a function. An array name can be named as an argument for the prototype declaration and in function header. When we call the function no need to subscript or square brackets. When we pass array that pass as a call by reference because the array name is address for that array. /* Program to illustrate passing array to function */ #include<stdio.h> void display(int) ; /* function prototype */ main( ) { int num[5] = {100, 20, 40, 15, 33, i ; clrscr( ) ; printf (“\n The content of array is \n”) ; for (i=0; i<5; i++) display (num[i]) ; /*Pass array element fo fun */ getch{ } ; } void display(int n) { printf (“\t%d”, n ) ; } Output:     The content of array is 100      20       40       15 3 /* Program to read 10 numbers from keyboard to store these num into array and then c...

CPU (Central Processing Unit)

PGA reffered as pin grid array in which pins of CPU are lined up in a straight format. SPGA referred as staggered pin grid array. in which pins of CPU are arranged staggered format. LGA reffered to as Land Grid Array in which pins are available within inside the socket but not in the CPU in other words in line grid array, in CPU ther are no pinsbut insteadpins areattached with in a socket which contact with with the CPU. for e.g. LGA775 socket(no pins on cpu) has better cooling system. better contact and better locking(climbing). LGA1155: Letest generation I socket, also reffered as sandy bridge, Turbo boost overclocking. More resent than LGA 1156 socket. LGA1156: ability to north bridge Doul channel DDR3 optional integreted graphics PCI express LGA1366: hi end core i series socket integreted tiple channal memmory controller external control bridge(HUB) Upgrading CPU: need to check its core suppert check multiprocessor supports or not check on the ...