The Wayback Machine - https://web.archive.org/web/20241109084055/https://www.geeksforgeeks.org/bank-account-system-in-c-using-file-handling/
Open In App

Bank account system in C using File handling

Last Updated : 26 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article focuses on how to create a bank account system using C language and File handling in C.

Approach:
Let’s discuss the approach in detail, covering all the functions and their explanation in detail-

  1. Create a Menu in the main function and create different functions for the Menu, which will be called using switch case statements. There are four different functions-
    1. account()- This function is used to create a new account.
    2. transfermoney()- This function is used to transfer money to the account
    3. checkbalance()- This function is used to check the balance in the account.
    4. login()- This function is used to login into the account.
  2. First, create an account of our user by calling the account() function after the creation of an account, store all the data into a file using file handling functions.
  3. Then the user is able to transfer the amount to other users, for that transfermoney() function is called, and for checking the current balance in the account call checkbalance() function.

Concepts of file handling will be used to store the data of the users, and then read all data from that particular file, store structures in a file because they are easy to write and read.

Implementation:
Let’s look at the C implementation of each of the modules of the program and finally consolidate all the modules together and create a full working program.

1. Create a Bank Account-
Take all the input from the user and make a structure for it to store the data in a file. 

// Function to create accounts 
// of users
void account(void)
{
 char password[20];
 int passwordlength, i, seek = 0;
 char ch;
 FILE *fp, *fu;
 struct pass u1;
 struct userpass p1;

 struct userpass u2;

 // Opening file to  
 // write data of a user
 fp = fopen("username.txt", "ab");

 // Inputs
 system("cls");
 printf("\n\n!!!!!CREATE ACCOUNT!!!!!");

 printf("\n\nFIRST NAME..");
 scanf("%s", &u1.fname);

 printf("\n\n\nLAST NAME..");
 scanf("%s", &u1.lname);

 printf("\n\nFATHER's NAME..");
 scanf("%s", &u1.fathname);

 printf("\n\nMOTHER's NAME..");
 scanf("%s", &u1.mothname);

 printf("\n\nADDRESS..");
 scanf("%s", &u1.address);

 printf("\n\nACCOUNT TYPE");
 scanf("%s", &u1.typeaccount);

 printf("\n\nDATE OF BIRTH..");
 printf("\nDATE-");
 scanf("%d", &u1.date);
 printf("\nMONTH-");
 scanf("%d", &u1.month);
 printf("\nYEAR-");
 scanf("%d", &u1.year);

 printf("\n\nADHAR NUMBER");
 scanf("%s", u1.adharnum);

 printf("\n\nPHONE NUMBER");
 scanf("%s", u1.pnumber);

 printf("\n\nUSERNAME.. ");
 scanf("%s", &u1.username);

 printf("\n\nPASSWORD..");

 // Taking password in the  
 // form of stars
 for (i = 0; i < 50; i++)  
 {
   ch = getch();
   if (ch != 13)  
   {
     password[i] = ch;
     ch = '*';
     printf("%c", ch);
   }
   else
     break;
 }

 // Writing to the file
 fwrite(&u1, sizeof(u1), 1, fp);

 // Closing file
 fclose(fp);

 // Calling another function  
 // after successful creation
 // of account
 accountcreated();
}

2. Transfer Money-
Take the username of another user to whom we want to transfer the money and open his record in the file and write the amount to the file.

// Function to transfer
// money from one user to
// another
void transfermoney(void)
{
 int i, j;
 FILE *fm, *fp;
 struct pass u1;
 struct money m1;
 char usernamet[20];
 char usernamep[20];
 system("cls");

 // Opening file in read mode to  
 // read user's username
 fp = fopen("username.txt", "rb");

 // Creating a another file  
 // to write amount along with
 // username to which amount  
 // is going to be transferred
 fm = fopen("mon.txt", "ab");

 gotoxy(33, 4);
 printf("---- TRANSFER MONEY ----");
 gotoxy(33, 5);
 printf("========================");

 gotoxy(33, 11);
 printf("FROM (your username).. ");
 scanf("%s", &usernamet);

 gotoxy(33, 13);
 printf(" TO (username of person)..");
 scanf("%s", &usernamep);

 // Checking for username if it  
 // is present in file or not
 while (fread(&u1, sizeof(u1), 1, fp))

 {
   if (strcmp(usernamep,
              u1.username) == 0)  
   {
     strcpy(m1.usernameto,
            u1.username);
     strcpy(m1.userpersonfrom,  
            usernamet);
   }
 }
 gotoxy(33, 16);

 // Taking amount input
 printf("ENTER THE AMOUNT TO BE TRANSFERRED..");
 scanf("%d", &m1.money1);

 // Writing to the file
 fwrite(&m1, sizeof(m1), 1, fm);

 gotoxy(0, 26);
 printf(
   "--------------------------------------------------"
   "--------------------------------------------");

 gotoxy(0, 28);
 printf(
   "--------------------------------------------------"
   "--------------------------------------------");

 gotoxy(0, 29);
 printf("transferring amount, Please wait..");

 gotoxy(10, 27);
 for (i = 0; i < 70; i++)
 {
   for (j = 0; j < 1200000; j++)  
   {
     j++;
     j--;
   }
   printf("*");
 }

 gotoxy(33, 40);
 printf("AMOUNT SUCCESSFULLY TRANSFERRED....");
 getch();

 // Close the files
 fclose(fp);
 fclose(fm);

 // Function to return  
 // to the home screen
 display(usernamet);
}

3. Check Balance-
Opening a file in which all the transfer records are written and read them one by one and match the username passed in the function to fetch the correct transfer records. 

// Function to check balance
// in users account
void checkbalance(char username2[])
{
 system("cls");
 FILE* fm;
 struct money m1;
 char ch;
 int i = 1, summoney = 0;

 // Opening amount file record
 fm = fopen("mon.txt", "rb");

 int k = 5, l = 10;
 int m = 30, n = 10;
 int u = 60, v = 10;

 gotoxy(30, 2);
 printf("==== BALANCE DASHBOARD ====");
 gotoxy(30, 3);
 printf("***************************");
 gotoxy(k, l);
 printf("S no.");
 gotoxy(m, n);
 printf("TRANSACTION ID");
 gotoxy(u, v);
 printf("AMOUNT");

 // Reading username to
 // fetch the correct record
 while (fread(&m1, sizeof(m1), 1, fm))  
 {
   if (strcmp(username2,  
              m1.usernameto) == 0)  
   {
     gotoxy(k, ++l);
     printf("%d", i);
     i++;
     gotoxy(m, ++n);
     printf("%s", m1.userpersonfrom);

     gotoxy(u, ++v);
     printf("%d", m1.money1);
     // adding and
     // finding total money
     summoney = summoney + m1.money1;
   }
 }

 gotoxy(80, 10);
 printf("TOTAL AMOUNT");

 gotoxy(80, 12);
 printf("%d", summoney);

 getch();

 // Closing file after  
 // reading it
 fclose(fm);
 display(username2);
}

4. Login Functionality-
To add Login functionality, we are opening the file and matching the username provided by the user at the time of registration, and logging in to him if the username is correct and matches with the record present in our file.

// Login function to check
// the username of the user
void login(void)
{
 system("cls");

 char username[50];
 char password[50];

 int i, j, k;
 char ch;
 FILE *fp, *fu;
 struct pass u1;
 struct userpass u2;

 // Opening file of
 // user data
 fp = fopen("username.txt", "rb");

 if (fp == NULL)  
 {
   printf("ERROR IN OPENING FILE");
 }
 
 gotoxy(34, 2);
 printf(" ACCOUNT LOGIN ");
 gotoxy(7, 5);
 printf("***********************************************"
        "********************************");

 gotoxy(35, 10);
 printf("==== LOG IN ====");

 // Take input
 gotoxy(35, 12);
 printf("USERNAME.. ");
 scanf("%s", &username);

 gotoxy(35, 14);
 printf("PASSWORD..");
 // Input the password
 for (i = 0; i < 50; i++)  
 {
   ch = getch();
   if (ch != 13)
   {
     password[i] = ch;
     ch = '*';
     printf("%c", ch);
   }

   else
     break;
 }

 // Checking if username
 // exists in the file or not
 while (fread(&u1,  
              sizeof(u1), 1, fp))  
 {
   if (strcmp(username,  
              u1.username) == 0)  
   {
     loginsu();
     display(username);
   }
 }

 // Closing the file
 fclose(fp);
}

// Screen is shown after  
// successful login
void loginsu(void)
{
 int i;
 FILE* fp;
 struct pass u1;
 system("cls");
 printf("Fetching account details.....\n");
 for (i = 0; i < 20000; i++)  
 {
   i++;
   i--;
 }
 gotoxy(30, 10);
 printf("LOGIN SUCCESSFUL....");
 gotoxy(0, 20);
 printf("Press enter to continue");

 getch();
}

Complete Program-
Below is the complete C program for the bank system using the concepts of file handling-

C




// C program to implement
// the above approach
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
 
// Declaring all the functions
void checkbalance(char*);
void transfermoney(void);
void display(char*);
void person(char*);
void login(void);
void loginsu(void);
void account(void);
void accountcreated(void);
void afterlogin(void);
void logout(void);
 
// Declaring gotoxy
// function for setting
// cursor position
void gotoxy(int x, int y)
{
    COORD c;
    c.X = x;
    c.Y = y;
 
    SetConsoleCursorPosition(
        GetStdHandle(STD_OUTPUT_HANDLE), c);
}
 
// Creating a structure to store
// data of the user
struct pass {
    char username[50];
    int date, month, year;
    char pnumber[15];
    char adharnum[20];
    char fname[20];
    char lname[20];
    char fathname[20];
    char mothname[20];
    char address[50];
    char typeaccount[20];
};
 
// Structure to keep track
// of amount transfer
struct money {
    char usernameto[50];
    char userpersonfrom[50];
    long int money1;
};
 
struct userpass {
    char password[50];
};
 
// Driver Code
int main()
{
    int i, a, b, choice;
    int passwordlength;
 
    gotoxy(20, 3);
 
    // Creating a Main
    // menu for the user
    printf("WELCOME TO BANK ACCOUNT SYSTEM\n\n");
    gotoxy(18, 5);
 
    printf("**********************************");
    gotoxy(25, 7);
 
    printf("DEVELOPER-Naman kumar");
 
    gotoxy(20, 10);
    printf("1.... CREATE A BANK ACCOUNT");
 
    gotoxy(20, 12);
    printf("2.... ALREADY A USER? SIGN IN");
    gotoxy(20, 14);
    printf("3.... EXIT\n\n");
 
    printf("\n\nENTER YOUR CHOICE..");
 
    scanf("%d", &choice;);
 
    switch (choice) {
    case 1:
        system("cls");
        printf("\n\n USERNAME 50 CHARACTERS MAX!!");
        printf("\n\n PASSWORD 50 CHARACTERS MAX!!");
        account();
        break;
 
    case 2:
        login();
        break;
 
    case 3:
        exit(0);
        break;
 
        getch();
    }
}
 
// Function to create accounts
// of users
void account(void)
{
    char password[20];
    int passwordlength, i, seek = 0;
    char ch;
    FILE *fp, *fu;
    struct pass u1;
    struct userpass p1;
 
    struct userpass u2;
 
    // Opening file to
    // write data of a user
    fp = fopen("username.txt", "ab");
 
    // Inputs
    system("cls");
    printf("\n\n!!!!!CREATE ACCOUNT!!!!!");
 
    printf("\n\nFIRST NAME..");
    scanf("%s", &u1.fname;);
 
    printf("\n\n\nLAST NAME..");
    scanf("%s", &u1.lname;);
 
    printf("\n\nFATHER's NAME..");
    scanf("%s", &u1.fathname;);
 
    printf("\n\nMOTHER's NAME..");
    scanf("%s", &u1.mothname;);
 
    printf("\n\nADDRESS..");
    scanf("%s", &u1.address;);
 
    printf("\n\nACCOUNT TYPE");
    scanf("%s", &u1.typeaccount;);
 
    printf("\n\nDATE OF BIRTH..");
    printf("\nDATE-");
    scanf("%d", &u1.date;);
    printf("\nMONTH-");
    scanf("%d", &u1.month;);
    printf("\nYEAR-");
    scanf("%d", &u1.year;);
 
    printf("\n\nADHAR NUMBER");
    scanf("%s", u1.adharnum);
 
    printf("\n\nPHONE NUMBER");
    scanf("%s", u1.pnumber);
 
    printf("\n\nUSERNAME.. ");
    scanf("%s", &u1.username;);
 
    printf("\n\nPASSWORD..");
 
    // Taking password in the form of
    // stars
    for (i = 0; i < 50; i++) {
        ch = getch();
        if (ch != 13) {
            password[i] = ch;
            ch = '*';
            printf("%c", ch);
        }
        else
            break;
    }
 
    // Writing to the file
    fwrite(&u1;, sizeof(u1),
           1, fp);
 
    // Closing file
    fclose(fp);
 
    // Calling another function
    // after successful creation
    // of account
    accountcreated();
}
 
// Successful account creation
void accountcreated(void)
{
    int i;
    char ch;
    system("cls");
    printf(
        "PLEASE WAIT....\n\nYOUR DATA IS PROCESSING....");
    for (i = 0; i < 200000000; i++) {
        i++;
        i--;
    }
 
    gotoxy(30, 10);
 
    printf("ACCOUNT CREATED SUCCESSFULLY....");
    gotoxy(0, 20);
 
    printf("Press enter to login");
 
    getch();
    login();
}
 
// Login function to check
// the username of the user
void login(void)
{
    system("cls");
 
    char username[50];
    char password[50];
 
    int i, j, k;
    char ch;
    FILE *fp, *fu;
    struct pass u1;
    struct userpass u2;
 
    // Opening file of
    // user data
    fp = fopen("username.txt",
               "rb");
 
    if (fp == NULL) {
        printf("ERROR IN OPENING FILE");
    }
    gotoxy(34, 2);
    printf(" ACCOUNT LOGIN ");
    gotoxy(7, 5);
    printf("***********************************************"
           "********************************");
 
    gotoxy(35, 10);
    printf("==== LOG IN ====");
 
    // Take input
    gotoxy(35, 12);
    printf("USERNAME.. ");
    scanf("%s", &username;);
 
    gotoxy(35, 14);
    printf("PASSWORD..");
 
    // Input the password
    for (i = 0; i < 50; i++) {
        ch = getch();
        if (ch != 13) {
            password[i] = ch;
            ch = '*';
            printf("%c", ch);
        }
 
        else
            break;
    }
 
    // Checking if username
    // exists in the file or not
    while (fread(&u1;, sizeof(u1),
                 1, fp)) {
        if (strcmp(username,
                   u1.username)
            == 0) {
            loginsu();
            display(username);
        }
    }
 
    // Closing the file
    fclose(fp);
}
 
// Redirect after
// successful login
void loginsu(void)
{
    int i;
    FILE* fp;
    struct pass u1;
    system("cls");
    printf("Fetching account details.....\n");
    for (i = 0; i < 20000; i++) {
        i++;
        i--;
    }
 
    gotoxy(30, 10);
    printf("LOGIN SUCCESSFUL....");
    gotoxy(0, 20);
    printf("Press enter to continue");
 
    getch();
}
 
// Display function to show the
// data of the user on screen
void display(char username1[])
{
    system("cls");
    FILE* fp;
    int choice, i;
    fp = fopen("username.txt", "rb");
    struct pass u1;
 
    if (fp == NULL) {
        printf("error in opening file");
    }
 
    while (fread(&u1;, sizeof(u1),
                 1, fp)) {
        if (strcmp(username1,
                   u1.username)
            == 0) {
            gotoxy(30, 1);
            printf("WELCOME, %s %s",
                   u1.fname, u1.lname);
            gotoxy(28, 2);
            printf("..........................");
            gotoxy(55, 6);
            printf("==== YOUR ACCOUNT INFO ====");
            gotoxy(55, 8);
            printf("***************************");
            gotoxy(55, 10);
            printf("NAME..%s %s", u1.fname,
                   u1.lname);
 
            gotoxy(55, 12);
            printf("FATHER's NAME..%s %s",
                   u1.fathname,
                   u1.lname);
 
            gotoxy(55, 14);
            printf("MOTHER's NAME..%s",
                   u1.mothname);
 
            gotoxy(55, 16);
            printf("ADHAR CARD NUMBER..%s",
                   u1.adharnum);
 
            gotoxy(55, 18);
            printf("MOBILE NUMBER..%s",
                   u1.pnumber);
 
            gotoxy(55, 20);
            printf("DATE OF BIRTH.. %d-%d-%d",
                   u1.date, u1.month, u1.year);
 
            gotoxy(55, 22);
            printf("ADDRESS..%s", u1.address);
 
            gotoxy(55, 24);
            printf("ACCOUNT TYPE..%s",
                   u1.typeaccount);
        }
    }
 
    fclose(fp);
 
    gotoxy(0, 6);
 
    // Menu to perform different
    // actions by user
    printf(" HOME ");
    gotoxy(0, 7);
    printf("******");
    gotoxy(0, 9);
    printf(" 1....CHECK BALANCE");
    gotoxy(0, 11);
    printf(" 2....TRANSFER MONEY");
    gotoxy(0, 13);
    printf(" 3....LOG OUT\n\n");
    gotoxy(0, 15);
    printf(" 4....EXIT\n\n");
 
    printf(" ENTER YOUR CHOICES..");
    scanf("%d", &choice;);
 
    switch (choice) {
    case 1:
        checkbalance(username1);
        break;
 
    case 2:
        transfermoney();
        break;
 
    case 3:
        logout();
        login();
        break;
 
    case 4:
        exit(0);
        break;
    }
}
 
// Function to transfer
// money from one user to
// another
void transfermoney(void)
{
    int i, j;
    FILE *fm, *fp;
    struct pass u1;
    struct money m1;
    char usernamet[20];
    char usernamep[20];
    system("cls");
 
    // Opening file in read mode to
    // read user's username
    fp = fopen("username.txt", "rb");
 
    // Creating a another file
    // to write amount along with
    // username to which amount
    // is going to be transferred
    fm = fopen("mon.txt", "ab");
 
    gotoxy(33, 4);
    printf("---- TRANSFER MONEY ----");
    gotoxy(33, 5);
    printf("========================");
 
    gotoxy(33, 11);
    printf("FROM (your username).. ");
    scanf("%s", &usernamet;);
 
    gotoxy(33, 13);
    printf(" TO (username of person)..");
    scanf("%s", &usernamep;);
 
    // Checking for username if it
    // is present in file or not
    while (fread(&u1;, sizeof(u1),
                 1, fp))
 
    {
        if (strcmp(usernamep,
                   u1.username)
            == 0) {
            strcpy(m1.usernameto,
                   u1.username);
            strcpy(m1.userpersonfrom,
                   usernamet);
        }
    }
    gotoxy(33, 16);
 
    // Taking amount input
    printf("ENTER THE AMOUNT TO BE TRANSFERRED..");
    scanf("%d", &m1.money1;);
 
    // Writing to the file
    fwrite(&m1;, sizeof(m1),
           1, fm);
 
    gotoxy(0, 26);
    printf(
        "--------------------------------------------------"
        "--------------------------------------------");
 
    gotoxy(0, 28);
    printf(
        "--------------------------------------------------"
        "--------------------------------------------");
 
    gotoxy(0, 29);
    printf("transferring amount, Please wait..");
 
    gotoxy(10, 27);
    for (i = 0; i < 70; i++) {
        for (j = 0; j < 1200000; j++) {
            j++;
            j--;
        }
        printf("*");
    }
 
    gotoxy(33, 40);
    printf("AMOUNT SUCCESSFULLY TRANSFERRED....");
    getch();
 
    // Close the files
    fclose(fp);
    fclose(fm);
 
    // Function to return
    // to the home screen
    display(usernamet);
}
 
// Function to check balance
// in users account
void checkbalance(char username2[])
{
    system("cls");
    FILE* fm;
    struct money m1;
    char ch;
    int i = 1, summoney = 0;
 
    // Opening amount file record
    fm = fopen("mon.txt", "rb");
 
    int k = 5, l = 10;
    int m = 30, n = 10;
    int u = 60, v = 10;
 
    gotoxy(30, 2);
    printf("==== BALANCE DASHBOARD ====");
    gotoxy(30, 3);
    printf("***************************");
    gotoxy(k, l);
    printf("S no.");
    gotoxy(m, n);
    printf("TRANSACTION ID");
    gotoxy(u, v);
    printf("AMOUNT");
 
    // Reading username to
    // fetch the correct record
    while (fread(&m1;, sizeof(m1),
                 1, fm)) {
        if (strcmp(username2,
                   m1.usernameto)
            == 0) {
            gotoxy(k, ++l);
            printf("%d", i);
            i++;
            gotoxy(m, ++n);
            printf("%s", m1.userpersonfrom);
 
            gotoxy(u, ++v);
            printf("%d", m1.money1);
            // Adding and
            // finding total money
            summoney = summoney + m1.money1;
        }
    }
 
    gotoxy(80, 10);
    printf("TOTAL AMOUNT");
 
    gotoxy(80, 12);
    printf("%d", summoney);
 
    getch();
 
    // Closing file after
    // reading it
    fclose(fm);
    display(username2);
}
 
// Logout function to bring
// user to the login screen
void logout(void)
{
    int i, j;
    system("cls");
    printf("please wait, logging out");
 
    for (i = 0; i < 10; i++) {
        for (j = 0; j < 25000000; j++) {
            i++;
            i--;
        }
        printf(".");
    }
 
    gotoxy(30, 10);
    printf("Sign out successfully..\n");
 
    gotoxy(0, 20);
    printf("press any key to continue..");
 
    getch();
}


Output

Output of the Program 



Previous Article
Next Article

Similar Reads

C | File Handling | Question 1
Which of the following true about FILE *fp (A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type (C) FILE is a stream (D) FILE is a buffered stream Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store followin
1 min read
C | File Handling | Question 2
When fopen() is not able to open a file, it returns (A) EOF (B) NULL (C) Runtime Error (D) Compiler Dependent Answer: (B) Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.Quiz of this Question
1 min read
C | File Handling | Question 3
getc() returns EOF when (A) End of files is reached (B) When getc() fails to read a character (C) Both of the above (D) None of the above Answer: (C) Explanation: See EOF, getc() and feof() in CQuiz of this Question
1 min read
C | File Handling | Question 4
In fopen(), the open mode "wx" is sometimes preferred "w" because. 1) Use of wx is more efficient. 2) If w is used, old contents of file are erased and a new empty file is created. When wx is used, fopen() returns NULL if file already exists. (A) Only 1 (B) Only 2 (C) Both 1 and 2 (D) Neither 1 nor 2 Answer: (B) Explanation: See https://www.geeksfo
1 min read
C | File Handling | Question 5
fseek() should be preferred over rewind() mainly because (A) rewind() doesn't work for empty files (B) rewind() may fail for large files (C) In rewind, there is no way to check if the operations completed successfully (D) All of the above Answer: (C) Explanation: Please see fseek() vs rewind() in CQuiz of this Question
1 min read
Basics of File Handling in C#
Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operation which is mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for
3 min read
Four File Handling Hacks which every C/C++ Programmer should know
We will discuss about four file hacks listed as below- Rename - Rename a file using C/C++Remove – Remove a file using C/C++File Size - Get the file size using C/C++Check existence – Check whether a file exists or not in C/C++ C/C++ Code // C++ Program to demonstrate the // four file hacks every C/C++ must know // Note that we are assuming that the
3 min read
Basics of File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Why do we need File Handling in C?So far the operations using the
15 min read
C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
Exception Handling and Object Destruction in C++
An exception is termed as an unwanted error that arises during the runtime of the program. The practice of separating the anomaly-causing program/code from the rest of the program/code is known as Exception Handling. An object is termed as an instance of the class which has the same name as that of the class. A destructor is a member function of a
4 min read
C++ | Exception Handling | Question 1
#include <iostream> using namespace std; int main() { int x = -1; try { cout << "Inside try \n"; if (x < 0) { throw x; cout << "After throw \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch \n"; return 0; } (A) Inside try Exception Caught After th
1 min read
C++ | Exception Handling | Question 3
What should be put in a try block? 1. Statements that might cause exceptions 2. Statements that should be skipped in case of an exception (A) Only 1 (B) Only 2 (C) Both 1 and 2 Answer: (C)Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem occurred, are put in
1 min read
C++ | Exception Handling | Question 4
Output of following program #include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; try { throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { cout<<"Caught Derived Exception"; } return 0; } (A) Caught Derived Exception (B) Caught B
1 min read
C++ | Exception Handling | Question 5
#include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int param) { cout << "int exception\n"; } catch (...) { cout << "default exception\n"; } cout << "After Exception"; return 0; } (A) default exception After Exception (B) int exception After Exception (C) int exceptio
1 min read
C++ | Exception Handling | Question 6
#include <iostream> using namespace std; int main() { try { throw 10; } catch (...) { cout << "default exception\n"; } catch (int param) { cout << "int exception\n"; } return 0; } (A) default exception (B) int exception (C) Compiler Error Answer: (C) Explanation: It is compiler error to put catch all block befo
1 min read
C++ | Exception Handling | Question 7
#include <iostream> using namespace std; int main() { try { try { throw 20; } catch (int n) { cout << "Inner Catch\n"; throw; } } catch (int x) { cout << "Outer Catch\n"; } return 0; } (A) Outer Catch (B) Inner Catch (C) Inner Catch Outer Catch (D) Compiler Error Answer: (C) Explanation: The statement 'throw;'
1 min read
C++ | Exception Handling | Question 8
#include <iostream> using namespace std; class Test { public: Test() { cout << "Constructing an object of Test " << endl; } ~Test() { cout << "Destructing an object of Test " << endl; } }; int main() { try { Test t1; throw 10; } catch(int i) { cout << "Caught " << i << en
1 min read
C++ | Exception Handling | Question 9
#include <iostream> using namespace std; class Test { static int count; int id; public: Test() { count++; id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; } ~Test() { cout << "Destructing object number " << id << endl; } }; int Test::count = 0; int ma
2 min read
C++ | Exception Handling | Question 10
Which of the following is true about exception handling in C++? 1) There is a standard exception class like Exception class in Java. 2) All exceptions are unchecked in C++, i.e., compiler doesn't check if the exceptions are caught or not. 3) In C++, a function can specify the list of exceptions that it can throw using comma separated list like foll
1 min read
C++ | Exception Handling | Question 11
What happens in C++ when an exception is thrown and not caught anywhere like following program. #include <iostream> using namespace std; int fun() throw (int) { throw 10; } int main() { fun(); return 0; } (A) Compiler error (B) Abnormal program termination (C) Program doesn't print anything and terminates normally (D) None of the above Answer
1 min read
C++ | Exception Handling | Question 12
What happens when a function throws an error but doesn't specify it in the list of exceptions it can throw. For example, what is the output of following program? #include <iostream> using namespace std; // Ideally it should have been "int fun() (int)" int fun() { throw 10; } int main() { try { fun(); } catch (int ) { cout <<
1 min read
Error Handling in C
Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors in the first place and test return values from the functions. A lot of C function calls return -1 or NULL or set an in case of an error code as the global variable err
8 min read
Socket Programming in C/C++: Handling multiple clients on server without multi threading
This tutorial assumes you have a basic knowledge of socket programming, i.e you are familiar with basic server and client model. In the basic model, server handles only one client at a time, which is a big assumption if you want to develop any scalable server model. The simple way to handle multiple clients would be to spawn new thread for every ne
9 min read
Exception Handling in C++
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code. So basica
11 min read
Print "Hello World" in C/C++ without using any header file
Write a C/C++ program that prints Hello World without including any header file. Conceptually it's seems impractical to write a C/C++ program that print Hello World without using a header file of "stdio.h". Since the declaration of printf() function contains in the "stdio.h" header file. But we can easily achieve this by taking the advantage of C p
2 min read
Getting System and Process Information Using C Programming and Shell in Linux
Whenever you start a new process in Linux it creates a file in /proc/ folder with the same name as that of the process id of the process. In that folder, there is a file named "status" which has all the details of the process. We can get those Process Information Through shell as follows: cat /proc/1/status As can be seen, it displays most of the i
2 min read
C program to delete a file
The remove() function in C/C++ can be used to delete a file. The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined inside the <stdio.h> header file. Syntax of remove()remove("filename");ParametersThis function takes a string as a parameter, which represents the name of the
2 min read
Difference between Header file and Library
Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi
3 min read
What is data type of FILE in C ?
Prerequisite : Basics of File Handling In C language, while file handling is done a word FILE is used. What is FILE? Example FILE *fp1, *fp2; While doing file handling we often use FILE for declaring the pointer in order to point to the file we want to read from or to write on. As we are declaring the pointer of type FILE so we can say it is data t
3 min read
LEX code to extract HTML tags from a file
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Approach: The extraction is based on the way tags are w
1 min read
Article Tags :
three90RightbarBannerImg