File handling
  • In C language, a file is a sequence of bytes.
  • It is used to store information.
  • If the data displayed is extensive, we want to access it again and again. Here comes the use of file handling because only a limited amount of data can be displayed on the console, and even memory is volatile.
  • In C, File handling allows us to create, read, update and delete the files stored on the local file system.

Operations on a file:

  • Creation of the new file.
  • Opening an existing file.
  • Reading from the file.
  • Writing to the file.
  • Closing or Deleting the file.
  • Files in C require the header.
  • The C file system includes various interrelated functions. The most common of these functions are shown. 

Name                                        Function 

fopen( )                                     It opens a file. 

fclose( )                                     It closes a file.

putc( )                                       It writes a character to a file.

fputc( )                                      It is same as putc( ). 

getc( )                                       It reads a character from a file. 

fgetc( )                                      It is similar to getc( ). 

fgets( )                                      It reads a string from the file. 

fputs( )                                      It writes a string to a file. 

fseek( )                                     It seeks to a specified byte in a file. 

ftell( )                                        It returns the current file position. 

fprintf( )                                     It writes data into the file.

fscanf( )                                    It reads data from the file.

feof( )                                        It returns true if end-of-file is reached.

ferror( )                                     It returns true if an error has occurred. 

rewind( )                                   It resets the file position indicator to the beginning

                                                 of the file.

remove( )                                  It erases a file. 

fflush( )                                     It flushes a file. 

File Pointer:

  • A file pointer points to the information that defines numerous things about the file, like file name, current position, and file status.
  • To read or write files, we need to use file pointers.

          Syntax:

                         FILE *fp;

Opening a File:

          Inorder tp open a file, fopen( ) function is used.  

Syntax:

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

                Here, file_name is a pointer that points to a string of characters representing the file’s name and mode defining how the file will be opened.

The legal values for mode are:

Mode                         Meaning 

r                                 It opens a text file for reading.

w                                It creates a text file for writing.

a                                 Append to a text file.

rb                                It opens a binary file for reading.

wb                               It creates a binary file for writing.

ab                                It appends a binary file.

r+                                 It opens a text file for read/write. 

w+                                It creates a text file for read/write. 

a+                                 It appends or creates a text file for read/write.

r+b                                It opens a binary file for read/write.

w+b                               It creates a binary file for read/write.

a+b                                It Appends or creates a binary file for read/write.

Closing a File:

  • To close the file opened by a call fopen(), the function fclose( ) is used.
  • Failure to close a stream welcomes many sorts of troubles like data loss, file destruction, and other possible intermittent errors.

           Syntax: 

                           int fclose(FILE *fptr);

                           Here, fptr is the file pointer returned by the Call to fopen( ). 

                           If it returns a value of zero, then it implies that the close operation is successful, and if an error occurs, then the function returns EOF. 

Header Files
  • Every function defined in the C standard library has a header associated with it.
  • The headers that relate to the functions that we use in our programs are included using #include.
  • The headers perform two crucial roles:
  • many functions in the standard library work with their specific data types, to which our program must have access. These data types are defined in the header associated with each function.
  • One of the most common examples is the file system header, which provides the type FILE necessary for disk file operations.
  • The second reason to include headers is to obtain the prototypes for the standard library functions.

          Function prototypes allow stronger type checking to be performed by the compiler, although prototypes are optional technically.

Syntax: 

                 #include

                        or

                 #include “file”

Example:

                     #include  Supports the I/O system

                     #include  Miscellaneous declarations 

                     #include Supports string functions 

                     #iinclude  Supports system time functions

Macros
  • Macro is a mechanism that provides a string substitution, or it is a part of code that is replaced by the value of the macro. 
  • It can be achieved through #define.
  • It replaces the already existing part with another part of the macro definition before executing the program.
  • The first object can be a function type or an object.

           Syntax:

                           #define first_part second_part

           Example:

                            #define PI 3.14 

                            #define equation (a*b)+c

Program:

#include<stdio.h>
#define eqn a*b
int main()
{
    int a,b,c;
    printf("enter a,b elements:");
    scanf("%d %d",&a,&b);
    c=eqn;//replaces c=a*b before execution of program
    printf("The value of c is %d",c);
    return 0;
}
Output:
enter a,b elements:2 3
The value of c is 6
Bit-Fields
  • A bit-field allows us to access a single bit.
  • It is a built-in feature of C.
  • Bit-fields can be used for the reasons such as:
  • If storage is limited, we can store several Boolean (true/false) variables in one byte.
  • The main idea of using bit-field is to utilize memory more efficiently when we know that the field value or group of fields will never exceed its limit or is within a small range.
  • Although we can perform these tasks using the bitwise operators, a bit-field can add more structure (and possibly efficiency) to our code.
  • A bit-field must be a part of a union or structure.
  • It shows how long (in bits) the field is to be.

          Syntax:

                        type name: length;

                         where type is the type of the bit-field, and it must be int, signed, or unsigned, and length is the number of bits in the field.

Example:

#include<stdio.h>
#include<string.h>
//a simple structure
struct
{
    unsigned int x;
    unsigned int y;
} first;
//creating a structure with bit fields
struct
{
    unsigned int x : 1;
    unsigned int y : 1;
} second;
int main()
{
    printf("Memory size occupied by first: %d\n", sizeof(first));
    printf("Memory size occupied by second: %d\n", sizeof(second));
    return 0;
}
Output:
Memory size occupied by first: 8
Memory size occupied by second: 4
 Dynamic Memory Allocation
  • Dynamic memory allocation allows the C programmer to allocate memory at runtime.
  • As we already know that an array is a set of a fixed number of values. Once the array size is declared, we cannot modify it, but sometimes the array we declared may be insufficient. To solve this issue, we can allocate memory manually during runtime. 
  • Dynamic memory allocation is done using standard library functions:
  1. malloc()
  2. calloc()
  3. realloc()
  4. free()

malloc():

  • “malloc” stands for memory allocation.
  • The malloc() function allocates a single block of memory requested.
  • Initially, it has a garbage value because it doesn’t initialize memory at execution time. 

          Syntax:

                       ptr = (type*) malloc(size);

          Example:

                          ptr = (int*) malloc(100 * sizeof(int));

calloc():

  • “calloc” stands for contiguous allocation.
  • The calloc() function allocates multiple blocks of memory requested.
  • Initially, it initializes all bytes to zero.

          Syntax:

                       ptr = (type*) calloc(n, size);

          Example:

                          ptr = (int*) calloc(25, sizeof(int));

realloc():

  • realloc() stands reallocation.
  • It reallocates the memory occupied by malloc() or calloc() functions, i.e.,
  • Using the realloc() function, we can change the size of previously allocated memory.

          Syntax:

                       ptr = realloc(ptr, x);

free():

  • Dynamically allocated memory created using either malloc() or calloc() does not get released on its own.
  • We must explicitly use free() to free the space.

          Syntax:

                         free(ptr);

Program 1: malloc() and free()

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,i,*p,sum=0;
    printf("Enter no. of elements:");
    scanf("%d",&n);
    p=(int*)malloc(n*sizeof(int));
    if(p==NULL)
    {
        printf("Unable to allocate memory");
        exit(0);
    }
    printf("Enter elements of array:");
    for(i=0;i<n;++i)
    {
        scanf("%d",p+i);
        sum+=*(p+i);
    }
    printf("Sum=%d",sum);
    free(p);
    return 0;
}
Output:
Enter no. of elements:3
Enter elements of array:0 1 2
Sum=3
Program 2: calloc() and realloc()
#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,i,*p;
    n=5;
    printf("Enter no. of elements: %d\n",n);
    p=(int*)calloc(n, sizeof(int));
    if(p==NULL)
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        printf("Memory successfully allocated.\n");
        for(i=0;i<n;++i)
        {
            p[i] = i +1;
        }
        printf("The elements of the array are:");
        for(i=0;i<n;++i)
        {
            printf("%d ",p[i]);
        }
        n=10;
        printf("\n\nEnter the new size of the array: %d\n", n);
        p = realloc(p, n * sizeof(int));
        printf("Memory successfully re-allocated.\n");
        for(i=5;i<n;++i)
        {
            p[i] = i + 1;
        }
        printf("The elements of the array are:");
        for(i=0;i<n;++i)
        {
            printf("%d ",p[i]);
        }
        free(p);
    }
    return 0;
}
Output:
Enter no. of elements: 5
Memory successfully allocated.
The elements of the array are:1 2 3 4 5
Enter the new size of the array: 10
Memory successfully re-allocated.
The elements of the array are:1 2 3 4 5 6 7 8 9 10

Who is the course for?

Prerequisites before starting this course:

Questions 🙵 Answers.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

More Courses

You might also be interested in these courses