Friday 22 April 2016

Get E-book of Gotfried on C programming

Click on the link
(Clicking on the link you will reach my another site & from there you can easily download E-book of Gotfried on C programming)

https://gopalbasak.wordpress.com/2016/04/22/get-e-book-of-gotfried-on-c-programming/

Get E-book of Dennis Ritchhe on C Programming

Click on the link (Clicking on link you will reach another site of mine & form there, you can directly download E-book of Dennis Ritchhe on C Programming).

Thursday 7 April 2016

File Handling or File Management in C

File Handling in C Language

file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the functions,
Functiondescription
fopen()create a new file or open a existing file
fclose()closes a file
getc()reads a character from a file
putc()writes a character to a file
fscanf()reads a set of data from a file
fprintf()writes a set of data to a file
getw()reads a integer from a file
putw()writes a integer to a file
fseek()set the position to desire point
ftell()gives current position in the file
rewind()set the position to the begining point

Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
modedescription
ropens a text file in reading mode
wopens or create a text file in writing mode.
aopens a text file in append mode
r+opens a text file in both reading and writing mode
w+opens a text file in both reading and writing mode
a+opens a text file in both reading and writing mode
rbopens a binary file in reading mode
wbopens or create a binary file in writing mode
abopens a binary file in append mode
rb+opens a binary file in both reading and writing mode
wb+opens a binary file in both reading and writing mode
ab+opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File

In the above table we have discussed about various file I/O functions to perform reading and writing on file.getc() and putc() are simplest functions used to read and write individual characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
 FILE *fp;
 char ch;
 fp = fopen("one.txt", "w");
 printf("Enter data");
 while( (ch = getchar()) != EOF) {
    putc(ch,fp);
 }
 fclose(fp);
 fp = fopen("one.txt", "r");
 while( (ch = getc()) != EOF)
    printf("%c",ch);
 fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
struct emp
{
   char name[10];
   int age;
};

void main()
{
   struct emp e;
   FILE *p,*q;
   p = fopen("one.txt", "a");
   q = fopen("one.txt", "r");
   printf("Enter Name and Age");
   scanf("%s %d", e.name, &e.age);
   fprintf(p,"%s %d", e.name, e.age);
   fclose(p);
   do
   {
      fscanf(q,"%s %d", e.name, e.age);
      printf("%s %d", e.name, e.age);
   }
   while( !feof(q) );
   getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but in different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console usinf standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements, 
   number_of_elements, pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite() function. Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";   
FILE *bfp= fopen("test.txt", "wb");   
if (bfp) {     
   fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;     
   fclose(bfp) ;   
} 

fseek(), ftell() and rewind() functions

  • fseek() - It is used to move the reading control to different positions using fseek function.
  • ftell() - It tells the byte location of current position of cursor in file pointer.
  • rewind() - It moves the control to beginning of the file.

Some File Handling Program Examples

  • Create a File and Store Information in it
  • List all the Files present in a Directory
  • Finding Size of a File
  • Copy Content of one File into Another File
  • Reverse the Content of File and Print it

    Error Handling

    C language does not provide direct support for error handling. However few method and variable defined inerror.h header file can be used to point out error using return value of the function call. In C language, a function return -1 or NULL value in case of any error and a global variable errno is set with the error code. So the return value can be used to check error while programming.
    C language uses the following functions to represent error
    • perror() return string pass to it along with the textual represention of current errno value.
    • strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value.

    Example

    #include <stdio.h>       
    #include <errno.h>       
    #include <stdlib.h>       
    #include <string.h>       
     
    extern int errno;
     
    main( )
    {
      char *ptr = malloc( 1000000000UL);  //requesting to allocate 1gb memory space  
      if ( ptr == NULL )        //if memory not available, it will return null  
      {  
         puts("malloc failed");
         puts(strerror(errno));
         exit(EXIT_FAILURE); //exit status failure       
      }
      else
      {
         free( ptr);
         exit(EXIT_SUCCESS); //exit status Success       
      }
    }
    
    Here exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status.EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successfull exit. It is defined as 0. EXIT_Failureis used in case of any failure in the program. It is defined as -1.

    Dynamic Memory Allocation

    The process of allocating memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h.
    FunctionDescription
    malloc()allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space
    calloc()allocates space for an array of elements, initialize them to zero and then return a void pointer to the memory
    freereleases previously allocated memory
    reallocmodify the size of previously allocated space

    Memory Allocation Process

    Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in area called Stack. The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.
    dynamic memory allocation in c

    Allocating block of Memory

    malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.
    Example using malloc() :
    int *x;
    x = (int*)malloc(50 * sizeof(int));    //memory space allocated to variable x
    free(x);                    //releases the memory allocated to variable x
    
    calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to locate enough space it returns a NULL pointer.
    Example using calloc() :
    struct employee
    {
     char *name;
     int salary;
    };
    typedef struct employee emp;
    emp *e1;
    e1 = (emp*)calloc(30,sizeof(emp));
    
    realloc() changes memory size that is already allocated to a variable.
    Example using realloc() :
    int *x;
    x=(int*)malloc(50 * sizeof(int));
    x=(int*)realloc(x,100); //allocated a new memory to variable x
    

    Diffrence between malloc() and calloc()

    calloc()malloc()
    calloc() initializes the allocated memory with 0 value.malloc() initializes the allocated memory with garbage values.
    Number of arguments is 2Number of argument is 1
    Syntax :
    (cast_type *)calloc(blocks , size_of_block);
    Syntax :
    (cast_type *)malloc(Size_in_bytes);

    Command Line Argument

    Command line argument is a parameter supplied to the program when it is invoked. Command line argument is an important concept in C programming. It is mostly used when you need to control your program from outside. command line arguments are passed to main() method.
    Syntax :
    int main( int argc, char *argv[])
    
    Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.

    Example for Command Line Argument

    #include <stdio.h>
    #include <conio.h>
    int main( int argc, char *argv[] )
    {
      int i;
      if( argc >= 2 )
       {
        printf("The arguments supplied are:\n");
        for(i=1;i< argc;i++)
        {
         printf("%s\t",argv[i]);
        }
       }
       else
       {
         printf("argument list is empty.\n");
       }
     getch();
     return 0;
    }
    
    Remember that argv[0] holds the name of the program and argv[1] points to the first command line argument and argv[n] gives the last argument. If no argument is supplied, argc will be one.

Pointer in C

Pointers

  Pointer are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers.
C uses pointers a lotWhy?:

  • It is the only way to express some computations.
  • It produces compact and efficient code.
  • It provides a very powerful tool.
C uses pointers explicitly with:

  • Arrays,
  • Structures,
  • Functions.
NOTE: Pointers are perhaps the most difficult part of C to understand. C's implementation is slightly different DIFFERENT from other languages.

What is a Pointer?

A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type.
The unary or monadic operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.
To declare a pointer to a variable do:
   int *pointer;
NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance.
Consider the effect of the following code:


   int x = 1, y = 2;
   int *ip;
 
   ip = &x;
 
y = *ip;  
x = ip;  
*ip = 3;
It is worth considering what is going on at the machine level in memory to fully understand how pointer work. Consider Fig. 9.1. Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000. Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new.
 
Fig. 9.1 Pointer, Variables and Memory Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip is declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the value 100.
Next y gets assigned to the contents of ip. In this example ip currently points to memory location 100 -- the location of x. So y gets assigned to the values of x -- which is 1.
We have already seen that C is not too fussy about assigning values of different type. Thus it is perfectly legal (although not all that common) to assign the current value of ip to x. The value of ip at this instant is 100.
Finally we can assign a value to the contents of a pointer (*ip).
IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it.
So ...


   int *ip;
 
   *ip = 100;
will generate an error (program crash!!).
The correct use is:

   int *ip;
   int x;
 
   ip = &x;
   *ip = 100;
We can do integer arithmetic on a pointer:

   float *flp, *flq;
 
   *flp = *flp + 10;
 
   ++*flp;
 
   (*flp)++;
 
   flq = flp;
NOTE: A pointer to any variable type is an address in memory -- which is an integer address. A pointer is definitely NOT an integer.
The reason we associate a pointer to a data type is so that it knows how many bytes the data is stored in. When we increment a pointer we increase the pointer by one ``block'' memory.
So for a character pointer ++ch_ptr adds 1 byte to the address.
For an integer or float ++ip or ++flp adds 4 bytes to the address.
Consider a float variable (fl) and a pointer to a float (flp) as shown in Fig. 9.2.
Fig. 9.2 Pointer Arithmetic Assume that flp points to fl then if we increment the pointer ( ++flp) it moves to the position shown 4 bytes on. If on the other hand we added 2 to the pointer then it moves 2 float positions i.e 8 bytes as shown in the Figure.




How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations −
#include <stdio.h>

int main () {

   int  var = 20;   /* actual variable declaration */
   int  *ip;        /* pointer variable declaration */

   ip = &var;  /* store address of var in pointer variable*/

   printf("Address of var variable: %x\n", &var  );

   /* address stored in pointer variable */
   printf("Address stored in ip variable: %x\n", ip );

   /* access the value using the pointer */
   printf("Value of *ip variable: %d\n", *ip );

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

NULL Pointers

It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program −
#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );
 
   return 0;
Download tutorial :  https://pdos.csail.mit.edu/6.828/2014/readings/pointers.pdf

Function in C

Functions in c

A function is a block of code that performs a particular task. There are times when we need to write a particular block of code for more than once in our program. This may lead to bugs and irritation for the programmer. C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space.
C functions can be classified into two categories,
  • Library functions
  • User-defined functions
types of functions in C
Library functions are those functions which are defined by C library, example printf()scanf()strcat() etc. You just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.

User-defined functions are those functions which are defined by the user at the time of writing program. Functions are made for code reusability and for saving time and space. 

EXAMPLES::

C Standard Library Functions

C Standard library functions or simply C Library functions are inbuilt functions in C programming. Function prototype and data definitions of these functions are written in their respective header file. For example: If you want to use printf() function, the header file <stdio.h> should be included.
#include <stdio.h>
int main()
    {

/* If you write printf() statement without including  header file, this program will show error. */
        printf("Catch me if you can."); 
    }
There is at least one function in any C program, i.e., the main() function (which is also a library function). This program is called at program starts.
There are many library functions available in C programming to help the programmer to write a good efficient program.
Suppose, you want to find the square root of a number. You can write your own piece of code to find square root but, this process is time consuming and the code you have written may not be the most efficient process to find square root. But, in C programming you can find the square root by just using sqrt() function which is defined under header file "math.h"

Use Of Library Function To Find Square root

#include <stdio.h>
#include <math.h>
int main(){
   float num,root;
   printf("Enter a number to find square root.");
   scanf("%f",&num);
   root=sqrt(num);          /* Computes the square root of num and stores in root. */
   printf("Square root of %.2f=%.2f",num,root);
   return 0;
}

Example of user-defined function

Write a C program to add two integers. Make a function add to add integers and display sum inmain() function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b);           //function prototype(declaration)
int main(){
     int num1,num2,sum;
     printf("Enters two number to add\n");
     scanf("%d %d",&num1,&num2);
     sum=add(num1,num2);         //function call 
     printf("sum=%d",sum); 
     return 0;
}
int add(int a,int b)            //function declarator
{             
/* Start of function definition. */
     int add;
     add=a+b;
     return add;                  //return statement of function 
/* End of function definition. */   
}                                  

Function prototype(declaration):

Every function in C programming should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type.

Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n) argument(n));
In the above example,int add(int a, int b); is a function prototype which provides following information to the compiler:
  1. name of the function is add()
  2. return type of the function is int.
  3. two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main() function.

Function call

Control of the program cannot be transferred to user-defined function unless it is called invoked.

Syntax of function call

function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); from main(). This make the control of program jump from that statement to function definition and executes the codes inside that function.

Function definition

Function definition contains programming codes to perform specific task.

Syntax of function definition

return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
                //body of function
}
Function definition has two major components:

1. Function declarator

Function declarator is the first line of function definition. When a function is called, control of the program is transferred to function declarator.

Syntax of function declarator

return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and declarator are almost same except, there is no semicolon at the end of declarator and function declarator is followed by function body.
In above example, int add(int a,int b) in line 12 is a function declarator.

2. Function body

Function declarator is followed by body of function inside braces.

Passing arguments to functions

In programming, argument(parameter) refers to data this is passed to function(function definition) while calling function.
In above example two variable, num1 and num2 are passed to function during function call and these arguments are accepted by arguments a and b in function definition. 
Passing argument/parameter through function in C
Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int and b should be of type float,i.e., type of argument during function call and function definition should be same.
A function can be called with or without an argument.

Return Statement

Return statement is used for returning a value from function definition to calling function.

Syntax of return statement

return (expression);     
For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in variable sum in main() function. The data type of expression in return statement should also match the return type of function.
Working of return statement in C

Recent Post

C videos in Hindi language

Hello friends , in the following links you will get whole C Programming videos in Hindi Language (availability is not guaranteed & th...

Popular Posts

visit counter