File handling in c

 

 



FILE HANDLING:


Different operations that can be performed on a file are: 
 

  1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w+”)
  2. Opening an existing file (fopen)
  3. Reading from file (fscanf or fgets)
  4. Writing to a file (fprintf or fputs)
  5. Moving to a specific location in a file (fseek, rewind)
  6. Closing a file (fclose)

 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``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 writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

OR

File opening modes in C: 
 

  • “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
  • “rb” – Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
  • “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  • “wb” – Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
  • “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  • “ab” – Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.
  • “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
  • “rb+” – Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
  • “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.
  • “wb+” – Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
  • “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  • “ab+” – Open for both reading and appending in binary mode. If the file does not exist, it will be created.


As given above, if you want to perform operations on a binary file, 
then you have to append ‘b’ at the last. For example,
 instead of “w”, you have to use “wb”, 
instead of “a+” you have to use “a+b”.
 For performing the operations on the file, a special pointer called File pointer is used which is declared as

FILE *filePointer; 

So, the file can be opened as 

filePointer = fopen(“fileName.txt”, “w”)

  • Reading from a file – 
    The file read operations can be performed using functions fscanf or fgets. Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer. So, it depends on you if you want to read the file line by line or character by character.
    And the code snippet for reading a file is as: 
     
FILE * filePointer; 

filePointer = fopen(“fileName.txt”, “r”);

fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
  • Writing a file –:
    The file write operations can be performed by the functions fprintf and fputs with similarities to read operations. The snippet for writing to a file is as : 
     
FILE *filePointer ; 

filePointer = fopen(“fileName.txt”, “w”);

fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
  • Closing a file –
    After every successful file operations, you must always close a file. For closing a file, you have to use fclose function. The snippet for closing a file is given as : 
     
FILE *filePointer ; 

filePointer= fopen(“fileName.txt”, “w”);

---------- Some file Operations -------

fclose(filePointer)





WRITING IN FILE:

1st ly we need to textfile so we can save given file with extension textfile.txt

textfile.txt :

hey meave good morning...

fputc function in file handling:

//write character in file
/*
  if we want write in file then use some functions
   1.fputc  --> for writing only character
   2.fputs  --> for writing string
   3.fprintf--> for used to print content in file instead of stdout console.
             -  this is used for print mix data type like char,int,float
             -  formated output
             -  using formated specifier Like %d, %c, %f ,%s...
*/
//fputc using print the character in file..

#include<stdio.h>
 int main()
 {
    FILE *fp;
    char ch = 'j';
    fp = fopen("textfile.txt","w");
      if(fp == NULL)
        printf("file not exist!!");
       
    fputc(ch,fp);                    //syntax: fputc(variable_name , file_pointer);
   
    fclose(fp);
 }


OUTPUT:
                   j

textfile.txt :

                   j

Explation:

here we have to seen only output j because in given program write mode is assign so 

write mode can (over write) delete previous data and write new data.


//fputc using print the string in file..

#include<stdio.h>
#include<string.h>  //need for strlen function..
 int main()
 {
    FILE *fp;
    char str[40];
    fp = fopen("textfile.txt","w");
      if(fp==NULL)
        printf("file not exist!!");

      printf("\n Enter the String :");
      gets(str);
     
     for(int i=0; i!=strlen(str); i++)  //used loop for print all character in string..
       {
        fputc(str[i],fp);
       }  
                                       //for line 16,17,18,19 instead write function fputs(str,fp);
    fclose(fp);
 }



OUTPUT:
                 Enter the String :The Shawshank redemption...


textfile.txt :

                 The Shawshank redemption...


puts function in file handling:

//write string in file
// fputs : syntax - fputs(variable_name , file_pointer);

#include<stdio.h>
int main()
{
    FILE *fp;
    char str[20] = "Learn world...";
    fp = fopen("textfile.txt","w");
    fputs(str,fp);
    fclose(fp);

}

OUTPUT:


textfile:

             Learn world...


fprintf function in file handling:

/* fprintf:
 write mix datatype in file
   fprintf--> for used to print content in file instead of stdout console.
             -  this is used for print mix data type like char,int,float
             -  formated output
             -  using formated specifier Like %d, %c, %f ,%s...
    syntax   : fprintf(file_pointer, format_specifiers.., variable_names..);
*/

#include<stdio.h>
 int main()
 {
    FILE *fp;
    char str[30] = "how are you";
    int a = 50;
    fp = fopen("textfile.txt","a");
    fprintf(fp, "%d %s", a,str);
    fclose(fp);
 }


OUTPUT:

textfile.txt:

                 Learn world...

                 50  here we are learning programming...


Explanation:
                         here we use append mode (a), append mode do not delete the previous data,

which is write the new data without deleting previous data...


READING IN FILE:

fgetc function in file handling:

//read in file
/*
  if we want read in file then use some functions
   1.fgetc  --> for read only character
   2.fgets  --> for read string
   3.fscanf--> for used to read content in file instead of stdout console.

*/
// fgetc :

 #include<stdio.h>
 int main()
 {
    FILE * fp;
    char ch;
    fp = fopen("textfile.txt","r");
       if(fp ==  NULL)
           printf("\n File not exist!!");
      ch = fgetc(fp);
      printf("%c",ch);
      fclose(fp);
 }


OUTPUT:

                L

textfile.txt :

                      Learn world...

                     50  here we are learning programming...

Explanation:

                   here print only L because fgetc function print only one character 

we have to print overall string then we need to loop..


// fgetc:
// print string using loop in fgetc..

#include<stdio.h>
 int main()
 {
    FILE * fp;
    char ch;
    fp = fopen("textfile.txt","r");
       if(fp ==  NULL)
           printf("\n File not exist!!");
      while(!feof(fp))
      {
       ch = fgetc(fp); // here read character and print one by one...
       printf("%c",ch);
      }
       fclose(fp);
 }


OUTPUT:

                   Learn world...

                  50  here we are learning programming...

textfile.txt :

                    Learn world...

                    50  here we are learning programming...

Explanation:

                 here print the overall string because we use loop using feof function (end of file).


fgets function in file handling:

// read string in file
// fgets:

 #include<stdio.h>
 int main()
 {
    FILE * fp;
    char str[30];
    fp = fopen("textfile.txt","r");
      fgets(str,30,fp);             // syntax: fgets(variable_name, size, file_pointer);
      printf("%s",str);
      fclose(fp);
 }

/*
here fgets(str,30,fp);
in this function str is function, 30 is size of length of string
if the size is 5 then print only Lear (4 character) because last character is \0.
*/

OUTPUT:

                Learn world...


textfile.txt :

                    Learn world...

                    50  here we are learning programming...

Explanation:

                      here print only Learn world... 
that means print only one line because fgets function print only one line using size...
The function reads characters from the file until either a newline .  


//fgets
//printf all lines using loop

// read string in file
// fgets:

 #include<stdio.h>
 int main()
 {
    FILE * fp;
    char str[30];
    fp = fopen("textfile.txt","r");
       if(fp == NULL)
          printf("\n file not exist!!");
      while(fp!=EOF)
      {
        fgets(str,30,fp);            
        printf("%s",str);
      }
      fclose(fp);
 }

OUTPUT:
                Learn world...

                50  here we are learning prog

textfile.txt :

                    Learn world...

                    50  here we are learning programming...

Explanation:

               here we have to seen print 1st line and print 29 character in 2nd line

because size is only 30 so print 29 character and last character is \0.

NOTE: Every line assign 30 character..


If we want to print overall string then we  need to increase size,,,

//fgets
//printf all lines using loop

// read string in file
// fgets:

 #include<stdio.h>
 int main()
 {
    FILE * fp;
    char str[50];
    fp = fopen("textfile.txt","r");
       if(fp == NULL)
          printf("\n file not exist!!");
      while(fp!=EOF)
      {
        fgets(str,50,fp);            
        printf("%s",str);
      }
      fclose(fp);
 }


OUTPUT:

                    Learn world...

                    50  here we are learning programming...

textfile.txt :

                    Learn world...

                    50  here we are learning programming...


r+ mode in file handling:

textfile: 

r+_file.txt

good morning...


// r+ mode in file handling
/*
  r+ mode can read and write operation perform
  if file does not exist then can't be create new file
  if file exist then do not erase previous data
  it is write in starting position in file using pointer..
  - if the modifing file then use the r+ mode
*/
 
 #include<stdio.h>
 int main()
 {
    FILE *fp;
     char ch, str[50];
    fp = fopen("r+_file.txt","r+");
     if(fp == NULL)
       printf("\n file not exist!!");
//write
     fputc('A',fp);    //here in txt file replace 1st word by 'A'.
     fputs("hey",fp);  //here in txt file replace character 2nd,3rd & 4th by hey.
  // fprintf(fp,"%d",5);
   
//read
/*
    while(!feof(fp))
      {
        ch = fgetc(fp);    //or //  fgets(str,50,fp);
        printf("%c",ch);   //or //  printf("%s",str);
      }
   here can't print anything because cursor will be in end of file
 (last position) in the file. while loop can't perform because false condition,
  so we need to cursor move to last to beginning, to read content..
  rewind(file_pointer); is a special function  to move cursor last to first..
 */
    rewind(fp);
    while(!feof(fp))
      {
        ch = fgetc(fp);    //or //  fgets(str,50,fp);
        printf("%c",ch);   //or //  printf("%s",str);
      }
   

    fclose(fp);  
 }

OUTPUT:

                Ahey morning...

mfiles.txt :

                Ahey morning...


w+ mode in file handling:

// w+ mode in file handling
/*
  w+ mode can read and write operation perform,
  but can't read previous data we can read only new data.
  if file does not exist then it can be create new file,
  if file exist then (overwrite) erase (delete) previous content (data),
  and after earasing data cursor will be in starting of file..    
*/
 
 #include<stdio.h>
 int main()
 {
    FILE *fp;
    char ch,str[50];
    fp = fopen("w+_file.txt","w+");
     if(fp == NULL)
       printf("\n file not exist!!");
//write
    fputc('s',fp);    
    fputs("hey",fp);  

//read
/*
    while(!feof(fp))
      {
        ch = fgetc(fp);    // fgets(str,50,fp);
        printf("%c",ch);   // printf("%s",str);
      }
 here can't print anything because cursor will be in end of file
 (last position) in the file. while loop can't perform because false condition,
  so we need to cursor move to last to beginning, to read content..
  rewind(file_pointer); is a special function  to move cursor last to first..
 */

   rewind(fp);
   while(!feof(fp))
      {
        ch = fgetc(fp);  //or  // fgets(str,50,fp);
        printf("%c",ch); //or  // printf("%s",str);
      }
 
   
    fclose(fp);  
 }


OUTPUT:

                   shey

w+_file.txt :

                 Learn with nil...


a+ mode in file handling:

/*a+ mode in file handling
 appending:
        appending means writing in ending of file

  a+ mode can read and append operation perform,
  but can't read previous data we can read only new data.
  if file does not exist then it can be create new file,
  if file exist then do not erase (delete) previous content (data),
 
*/
 
 #include<stdio.h>
 int main()
 {
    FILE *fp;
    char ch,str[50];
    fp = fopen("a+_file.txt","a+  ");
     if(fp == NULL)
       printf("\n file not exist!!");
//write
    fputc('s',fp);    
    fputs(" awesome",fp);  

//read
/*
    while(!feof(fp))
      {
        ch = fgetc(fp);    // fgets(str,50,fp);
        printf("%c",ch);   // printf("%s",str);
      }
 here can't print anything because cursor will be in end of file
 (last position) in the file. while loop can't perform because false condition,
  so we need to cursor move to last to beginning, to read content..
  rewind(file_pointer); is a special function  to move cursor last to first..
 */
 
   rewind(fp);
   while(!feof(fp))
      {
        ch = fgetc(fp);  //or  // fgets(str,50,fp);
        printf("%c",ch); //or  // printf("%s",str);
      }
 
    fclose(fp);  
 }

OUTPUT:

                hello guyes kaise ho...s awesome

a+_file.txt:

                hello guyes kaise ho...


 fseek function in file handling:

/* fseek function:
   used for move the cursome anywhere
   feek function already define in stdio.h library.
 syntax:  int fseek(file_pointer, offset,position/origin );
  Explaination:
   offset(return type- int,long): how many byte u want to move.
    - if u want to move forward, then offset value is positive
    - if u want to move backward then offset value is negative

   position(return type-int):from which position u want to add offset.
    positions functions:
    - SEEK_SET --> bigining of the file
    - SEEK_CUR --> current position of file pointer
    - SEEK_END --> end of the file
*/
//   fseek.txt :
// learn with nil is the best
// 0123456789..  <--index numbers

#include<stdio.h>
 int main()
 {
    FILE *fp;
    char ch;
    fp = fopen("fseek.txt","r");
      if(fp == NULL)
         printf("file not exist");
    fseek(fp,6,SEEK_SET);       //cursor from start position
     ch = fgetc(fp);
     printf("\n Character is: %c",ch);  //print w

    fseek(fp,-3,SEEK_CUR);     //cursor from current position
     ch = fgetc(fp);
     printf("\n Character is: %c",ch);  //print n
   
    fseek(fp,-3,SEEK_END);     //cursor from end position
     ch = fgetc(fp);
     printf("\n Character is: %c",ch);  //print e
 }

OUTPUT:

                 Character is: w

                 Character is: n

                 Character is: e

fseek.txt :

             learn with nil is the best


ftell function in file handling:

/* ftell function in file handling:
   - ftell function tell the position of file pointer.
   - return type ftell function int or long/.

*/
//   fseek.txt :
// learn with nil is the best
// 0123456789..  <--index numbers

#include<stdio.h>
 int main()
 {
    FILE *fp;
    int pos;
    char ch;
    char str[50];
    fp = fopen("fseek.txt","r");
      if(fp == NULL)
         printf("file not exist");
    pos = ftell(fp);
    printf("file pointer is : %d",pos); // output: o becaz mode is r

    fseek(fp,6,SEEK_SET);
    printf("\n now file pointer is: %d",ftell(fp)); // 6
   
    ch = fgetc(fp);
    printf("\n character is: %c",ch);           // w
    printf("\n file pointer is: %d",ftell(fp)); // 7
    printf("\n character is: %c",ch);           // w

    fgets(str, 50, fp);
    printf("\n string is: %s",str);             // ith nil is the best
    printf("\n file pointer is: %d",ftell(fp)); // 26

    fseek(fp,0,SEEK_END);
    printf("\n character is: %c",ch);           //w
    printf("\n file pointer is: %d",ftell(fp)); //26

   fclose(fp);
 }
   

OUTPUT:

                file pointer is : 0

                now file pointer is: 6        

                character is: w

                file pointer is: 7

                character is: w

                string is: ith nil is the best

                file pointer is: 26

                character is: w

                file pointer is: 26


fseek.txt:

                learn with nil is the best





















                                                                       end







Comments

  1. class MyNumber
    {
    int x ;
    MyNumber()
    {
    x = 0;
    }
    MyNumber(int x)
    {
    this.x = x;
    }
    void isNegative(int x)
    {
    if(x<0)
    System.out.println("no is negative");
    }

    void isPositive(int x)
    {
    if(x>=0)
    System.out.println("no is positive");
    }

    void isZero(int x)
    {
    if(x == 0)
    System.out.println("no is zero");
    }

    void isOdd(int x)
    {
    if(x%2 != 0)
    System.out.println("no is odd");
    }

    void isEven(int x)
    {
    if(x%2 == 0)
    System.out.println("no is even");
    }
    }

    class CheckNum
    {
    public static void main(String args[])
    {
    int x;
    x = Integer.parseInt(args[0]);
    MyNumber obj = new MyNumber(x);
    obj.isNegative(x);
    obj.isPositive(x);
    obj.isZero(x);
    obj.isOdd(x);
    obj.isEven(x);
    }
    }




    ReplyDelete
  2. import java.util.Date;
    import java.text.SimpleDateFormat;

    public class Datedemo
    {
    public static void main(String [] args)
    {
    Date d = new Date();
    //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    //String strdate =sdf.format(d);

    String strdate1 = new SimpleDateFormat("dd/MM/YYYY").format(d);
    System.out.println("current date:"+strdate1);

    String strdate2 = new SimpleDateFormat("MM/dd/yyyy").format(d);
    System.out.println("current date:"+strdate2);

    String strdate3 = new SimpleDateFormat("EEEE MMMM dd yyyy").format(d);
    System.out.println("current date:"+strdate3);

    String strdate4 = new SimpleDateFormat("EEEE MMMM hh:mm:ss a z yyyy").format(d);
    System.out.println("current date & time is:"+strdate4);


    String strdate5 = new SimpleDateFormat("hh:mm:ss").format(d);
    System.out.println("current time:"+strdate5);


    String strdate6 = new SimpleDateFormat("W").format(d);
    System.out.println("current week of year:"+strdate6);

    String strdate7 = new SimpleDateFormat("w").format(d);
    System.out.println("current week of month:"+strdate7);

    String strdate8 = new SimpleDateFormat("d").format(d);
    System.out.println("current day of manth:"+strdate8);

    String strdate9 = new SimpleDateFormat("D").format(d);
    System.out.println("current day of year:"+strdate9);

    }
    }

    ReplyDelete

Post a Comment

hey

Popular posts from this blog

Practical slips programs : Machine Learning

Full Stack Developement Practical Slips Programs

Android App Developement Practicals Programs