Showing posts with label File handling. Show all posts
Showing posts with label File handling. Show all posts

Wednesday, March 9, 2016

C program source code to create file in file handling

C program source code to create file in file handling


Write a C program  to create file in file handling

C Program source code

#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fptr;
fptr=fopen("Test.txt","w");
if(fptr==NULL)
{
printf("\nFile can not be opened");
}
else
{
printf("File is succesfully created");
}
fputs("welcome to c programming",fptr);
fclose(fptr);
getch();

return 0;

}



You can Browse related article below for more information and program code related to recursive function call

 Does above is helpful , Post you views in comment

DO NOT MISS OTHER C PROGRAMMING TUTORIAL

* indicates required



Sunday, March 6, 2016

File handling in c program - I








Filehandling in c program - I


WRITING TO AND READING FROM A FILE



#include                                                
                                                                    
   main()                                                           
   { 
       FILE *f1;                                                    
       char c;                                                      
       printf("Data Input\n\n");
    	 /* Open the file INPUT */                                     
       f1 = fopen("INPUT", "w");
    
   	 /* Get a character from keyboard   */                                                                   
       while((c=getchar()) != EOF) 

     /* Write a character to INPUT  */  
           putc(c,f1);     
       /* Close the file INPUT   */                                                                
       fclose(f1);                 
       printf("\nData Output\n\n"); 
       /* Reopen the file INPUT    */                             
       f1 = fopen("INPUT","r");    

      /* Read a character from INPUT*/                                                                  
       while((c=getc(f1)) != EOF) 

      /* Display a character on screen */  
           printf("%c",c);     

   /* Close the file INPUT       */  
       fclose(f1);                
   }                                                                


Output

Data Input
This is a program to test the file handling
features on this system^Z

Data Output
This is a program to test the file handling
features on this system

HANDLING OF INTEGER DATA FILES

A file named DATA contains a series of integer numbers. Code a program to read these numbers and then write all 'odd' numbers to a file to be called ODD and all `even' numbers to a file to be called EVEN.

It uses three files simultaneously and therefore we need to define three-file pointers f1, f2 and f3.

First, the file DATA containing integer values is created. The integer values are read from the terminal and are written to the file DATA with the help of the statement
putw(number, f1);
Notice that when we type -1, the reading is terminated and the file is closed. The next step is to open all the three files, DATA for reading, ODD and EVEN for writing. The contents of DATA file are read, integer by integer, by the function getw(f1) and written to ODD or EVEN file after an appropriate test. Note that the statement
(number = getw(f1)) != EOF
reads a value, assigns the same to number, and then tests for the end-of-file mark.

Finally, the program displays the contents of ODD and EVEN files. It is important to note that the files ODD and EVEN opened for writing are closed before they are reopened for reading.



#include                                                 
   main()                                                            
   {                                                                 
       FILE  *f1, *f2, *f3;                                          
       int   number, i;                                              
                                                                     
       printf("Contents of DATA file\n\n");                          
       f1 = fopen("DATA", "w");      /* Create DATA file    */       
       for(i = 1; i <= 30; i++)                                      
       {
          scanf("%d", &number);                                      
          if(number == -1) break;                                    
          putw(number,f1);                                           
       }                                                             
       fclose(f1);                                                   
                                                                     
       f1 = fopen("DATA", "r");                                      
       f2 = fopen("ODD", "w");                                       
       f3 = fopen("EVEN", "w");       
                               
       /* Read from DATA file */                                                                 
       while((number = getw(f1)) != EOF) 
       {
           if(number %2 == 0)                                        
             putw(number, f3);   /*  Write to EVEN file  */   
           else                                                      
             putw(number, f2);   /*  Write to ODD file   */   
       }                                                             
       fclose(f1);                                                   
       fclose(f2);                                                   
       fclose(f3);                                                   
                                                                     
       f2 = fopen("ODD","r");                                        
       f3 = fopen("EVEN", "r");                                      
       printf("\n\nContents of ODD file\n\n");                       
                                                                     
       while((number = getw(f2)) != EOF)                             
          printf("%4d", number);                                     
       printf("\n\nContents of EVEN file\n\n");                      
                                                                     
       while((number = getw(f3)) != EOF)                             
          printf("%4d", number);                                     
                                                                     
       fclose(f2);                                                   
       fclose(f3);                                                   
                                                                     
   }                                                                 

Output

Contents of DATA file 111 222 333 444 555 666 777 888 999 000 121 232 343 454 565 -1

 Contents of ODD file 111 333 555 777 999 121 343 565

Contents of EVEN file 222 444 666 888 0 232 454


ERROR HANDLING IN FILE OPERATIONS

Write a program to illustrate error handling in file operations.

The program the use of the NULL pointer test and feof function. When we input filename as TETS, the function call
fopen("TETS", "r");
returns a NULL pointer because the file TETS does not exist and therefore the message "Cannot open the file" is printed out.

Similarly, the call feof(fp2) returns a non-zero integer when the entire data has been read, and hence the program prints the message "Ran out of data" and terminates further reading.



#include                                               
                                                                    
    main()                                                          
    {                                                               
       char  *filename;                                            
        FILE  *fp1, *fp2;                                           
        int   i, number;                                            
                                                                    
        fp1 = fopen("TEST", "w");                                   
        for(i = 10; i <= 100; i += 10)                              
           putw(i, fp1);                                            
                                                                    
        fclose(fp1);                                                
                                                                    
        printf("\nInput filename\n");                               
                                                                    
    open_file:                                                      
        scanf("%s", filename);                                      
                                                                    
        if((fp2 = fopen(filename,"r")) == NULL)                     
        {                                                           
           printf("Cannot open the file.\n");                       
           printf("Type filename again.\n\n");                      
           goto open_file;                                          
        }                                                           
        else                                                        
                                                                    
        for(i = 1; i <= 20; i++)                                    
        {  number = getw(fp2);                                      
           if(feof(fp2))                                            
           {                                                        
              printf("\nRan out of data.\n");                       
              break;                                                
           }                                                        
           else                                                     
              printf("%d\n", number);                               
        }                                                           
                                                                    
        fclose(fp2);                                                
    }                                                               

Output

Input filename
 TETS
 Cannot open the file.
 Type filename again.
 TEST
 10
 20
 30
 40

APPENDING ITEMS TO AN EXISTING FILE

Write a program to append additional items to the file INVENTORY and print the total contents of the file.

It uses a structure definition to describe each item and a function append() to add an item to the file.

On execution, the program requests for the filename to which data is to be appended. After appending the items, the position of the last character in the file is assigned to n and then the file is closed.

The file is reopened for reading and its contents are displayed. Note that reading and displaying are done under the control of a while loop. The loop tests the current file position against n and is terminated when they become equal.

#include                                                
                                                                    
   struct invent_record                                             
   {
       char   name[10];                                             
       int    number;                                               
       float  price;                                                
       int    quantity;                                             
   };                                                               
                                                                    
   main()                                                           
   {
       struct invent_record item;                                   
       char  filename[10];                                          
       int   response;                                              
       FILE  *fp;                                                   
       long  n;                                                     
       void append (struct invent_record 8x, file *y);                                                             
       printf("Type filename:");                                    
       scanf("%s", filename);                                       
                                                                    
       fp = fopen(filename, "a+");                                  
       do                                                           
       {
          append(&item, fp);                                        
          printf("\nItem %s appended.\n",item.name);                
          printf("\nDo you want to add another item\                
   		(1 for YES /0 for NO)?");                                        
          scanf("%d", &response);                                   
       }  while (response == 1);                                    
                                                                    
       n = ftell(fp);      /* Position of last character  */        
       fclose(fp);                                                  
                                                                    
       fp = fopen(filename, "r");                                   
                            





                                        
       
  while(ftell(fp) < n)                                         
       {                                                            
          fscanf(fp,"%s %d %f %d",                                  
          item.name, &item.number, &item.price, &item.quantity); 
          fprintf(stdout,"%-8s %7d %8.2f %8d\n",                    
          item.name, item.number, item.price, item.quantity);    
       }                                                            
       fclose(fp);                                                  
   }                                                                
   void append(struct invent_record *product, File *ptr)
   {                                                                
       printf("Item name:");                                        
       scanf("%s", product->name);                                  
       printf("Item number:");                                      
       scanf("%d", &product->number);                               
       printf("Item price:");                                       
       scanf("%f", &product->price);                                
       printf("Quantity:");                                         
       scanf("%d", &product->quantity);                             
       fprintf(ptr, "%s %d %.2f %d",                                
                     product->name,                                 
                     product->number,                               
                     product->price,                                
                     product->quantity);                            
   }                                                                

Output

Type filename:INVENTORY
Item name:XXX
Item number:444
Item price:40.50
Quantity:34
Item XXX appended.
Do you want to add another item(1 for YES /0 for NO)?1
Item name:YYY
Item number:555
Item price:50.50
Quantity:45
Item YYY appended.
Do you want to add another item(1 for YES /0 for NO)?0


DO NOT MISS OTHER C PROGRAMMING TUTORIAL

* indicates required


Saturday, March 5, 2016

Opening a file in c






Opening a file in c



A file must be opened before any I/O operation can be performed on that file .

The process of establishing a connection between the program and the file is called opening the file

A structure named FILE Is defined in the file stdio.h that contains all information about the file like name , status , buffer size , current position , end of file status etc .

All these details are hidden from the programmer and the operating system takes care of all these things.

typedef  struct {
………….
……………
} FILE;

A file pointer is a pointer to a structure of type FILE . Whenever a file is opened , a structure of type FILE is associated with it , and a file pointer that points to this structure identifies this file .

The function fopen() is used to open a file

Declaration

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

fopen() function takes two string as arguments , the first one is the name of the file to be opened and the second one is the mode that describes which operations ( read , write , append etc) are to be performed on the file .

 On success , fopen() returns a pointer of type FILE and on error it returns NULL . The return value of fopen() is assigned to the pointer declared previously . For example


FILE *fp1 ,*fp2 ;
Fp1 = fopen(“myfile.txt”,”w”);
Fp2 = fopen(“myfile.dat”,”r”);


The name of the file is limited to FILENAME_MAX characters .

After opening the file with fopen() , the name of file is not used in the program for any operation on it .

whenever we have to performed any operation on the file we will use pointer returned by fopen() function .

 so the original name is called external name but the file pointer associated with it is called internal name.


The second argument represent the mode in which file is opened . The possible modes are :

“w”(write)

– If the file does not exit then this mode create a new file and if the file is already exist then previous data is erased and new data entered is written to the file

“a”(append)

- - If the file does not exit then this mode create a new file and if the file is already exist then new data is appended at the end of file . In this mode , the data existing in the file is not erased as in previous mode.

“r”(read)

-- This mode is used to read existing data in the file . File must exist for this operation and data is not erased

“w+”(write+read)

—This mode is similar to the write mode but here we can also read and modify the data . If the file does not exit then this mode create a new file and if the file is already exist then previous data is erased and new data entered is written to the file

“r+”(read+write)

—This mode is similar to the read mode but here we can also write and modify the data .File must exist for this operation and data is not erased . Since we can add new data and modify existing data so this mode is also called update mode.

“a+”(append+read)

—This mode is similar to the append mode but here we can also read the data stored in the file . If the file does not exit then this mode create a new file and if the file is already exist then new data is appended at the end of file . In this mode , the data existing in the file is not erased as in previous mode.

To open a file in binary mode we can append ‘b’ to the mode , and to open the file in text mode ‘t’ can be appended to the mode .

But since text mode is the default mode , ‘t’ is generally omitted while opening files in text mode . For example-

“wb” - Binary file opened in write mode

“ab+” or “a+b” - Binary file opened in append mode

Errors in Opening Files

If an error occurs in opening the file , than fopen() return null . So we can check for any errors in opening by checking the return value of fopen() .


FILE *fp ;
fp = fopen(“myfile.dat”,”w”);
if (fp == NULL)
{
printf(“error in opening file”);
exit(1);

}


Errors in opening a file may occur due to various reasons , for example-

1.If we try to open a file in a read or update mode , and the file does not exist or we do not have read permission on that file

2.If we try to create a file and there is no space on the disk , then we do not have write permission

3.Operating system limit the number of file that can be opened at a time and we are trying to open more file than that limit

Alert


We can give full pathname to open a file . Suppose we want to open a file DOS whose path is ”f:\file\myfile.dat” , then we have to write as –

fp = fopen(”f:\\file\\myfile.dat”, “r”);

Here we have used double backslash inside string is considered as an escape character , ‘\f’ and ‘\m’ are regarded as escape sequence if we use single backslash . In Unix , a single forward slash can be used

Never give the mode single quotes , since it is string not a character constant

fopen(”f:\\file\\myfile.dat”, ‘r’);  //ERROR


You can Browse related article below for more information and program code related to file handling Does above is helpful , Post you views in comment

DO NOT MISS OTHER C PROGRAMMING TUTORIAL

* indicates required





Difference between text file and binary file

Difference between text file and binary file

Difference between text file and binary file



There are two kinds of storing data in file text format and binary format .


 In text file data are stored as line of characters with each line terminated by a new line character (‘\n’). In binary format data is stored on the disk in the same way as it is represented in the computer memory . Unix system does not make any distinction between text file and binary file.


 Text file are in human readable form and they can be created and read using any text editor , while binary file are not in human readable form and they can be created and read only by specific program written for them .


The binary data stored in file can not be read using text editor. The hexadecimal value of 1679 is 0x068f , so in binary format it is represented by two bytes 0x06 and 0x8f . In a text file 1679 is represented by the bytes 0x31 , 0x36 , 0x37 ,0x39 ( ASCII values) . NOTE ASCII value for 1 is 31 and for 9 is 39.


 Both text file and binary file keep record of the length of the file , and identify the end of file when this is reached . In text files , there is one more way to detect the end of file. The character with ASCII value 26 is considered to be end of file character in text files . All input function stop reading character when this character is encountered and return end of file signal to the program . C does not insert this character in file , it can be entered through the keyboard by Ctrl + Z (Ctrl + D on some systems) . In binary files no such character represent end of file.

 In text files newline is stored as a combination of carriage return ‘\r’ (ASCII 13) and linefeed ‘\n’(ASCII 10) while in binary files newline is stored only as ‘\n’(ASCII 10).

 In binary format , the data is stored in the same way as it is represented in memory so no conversion s have to take place while transferring of data between memory and file . In text format some conversions have to take place while transferring of data between memory and file. For example while writing to a text file newline (‘\n’) has to be converted to combination of(‘\r’) and (‘\n’) and while reading from text file this combination (‘\r’) and (‘\n’) is to be converted back (‘\n’).

 The input and output operations in the binary files takes less time as compared to the text files because no conversion has to be take place . However the data written using binary file system is not very portable because size of data type and byte order may be different on different machines . In text format , these problems do not raise so it is considered more portable

You can Browse related article below for more information and program code related to file handling Does above is helpful , Post you views in comment

DO NOT MISS OTHER C PROGRAMMING TUTORIAL

* indicates required