Filehandling in c program - 1

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);                
   }                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

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.

(adsbygoogle = window.adsbygoogle || []).push({});

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);
1

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
1

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);                                                   
                                                                     
   }                                                                 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

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");
1

returns a NULL pointer because the file TETS does not exist and therefore the message "Cannot open the file" is printed out.

(adsbygoogle = window.adsbygoogle || []).push({});

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);                                                
    }                                                               
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

Output

Input filename

 TETS

 Cannot open the file.

 Type filename again.

 TEST

 10

 20

 30

 40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

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);                            
   }                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(adsbygoogle = window.adsbygoogle || []).push({});
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date(); (function(){ var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0]; s1.async=true; s1.src='https://embed.tawk.to/5bd7b562476c2f239ff683f0/default'; s1.charset='UTF-8'; s1.setAttribute('crossorigin','*'); s0.parentNode.insertBefore(s1,s0); })();
(adsbygoogle = window.adsbygoogle || []).push({});