4
\$\begingroup\$

I built my first program to solve an issue occurring at my self-owned business.. This program I made after learning a bit of C. It took about a month to make and what it performs is various functions within the program

mostly file operations,

  1. It takes and records an inventory of stock, the amount available for x stock the cost price, selling price and is saved to a file with the name of that stock

  2. After it takes those files and uses it as a source for my Point of sale function - i.e. pos() - which I made to be a virtual cash register of some sort records the transaction and saves it to a file to be later read

  3. Then it reads back the transaction as a proof of it occurring

  4. Tells me if I am suffering a debt or enjoying profits based on the price of the items and the selling price and the amount sold

Below is my code any critiques, comments or suggestions are appreciated thank you:

                              /*███████ ████████  █████  ██████  ████████      ██████  ███████     ███████ ██ ██      ███████ 
                                ██         ██    ██   ██ ██   ██    ██        ██    ██ ██          ██      ██ ██      ██      
                                ███████    ██    ███████ ██████     ██        ██    ██ █████       █████   ██ ██      █████   
                                     ██    ██    ██   ██ ██   ██    ██        ██    ██ ██          ██      ██ ██      ██      
                                ███████    ██    ██   ██ ██   ██    ██         ██████  ██          ██      ██ ███████ ███████ */





//VVVVVHEADERSVVVVV

/*A header file in C is the one in which it contains function declarations/ definitions,
variables and macro definitions
to be shared between several source files and has a filename with extension ".h".*/

/*-----------------------------------------------------------------------------------------------------------------*/
#include <stdio.h>//Including Standard Input Output,Allows program to take input and produce output as well,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <stdlib.h>//Including Standard library,Allows program to use unsigned interger types,NULL,malloc etc,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <string.h>//Including String, Allows program to use NULL,strcmp and strcpy and array allocation,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <windows.h>//Including Windows,Windows-specific header file for C allowing for sleep(),Handle,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <unistd.h>//Including C POSIX library,Allows program to use NULL,write,FILE management,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <conio.h>//Including Console Input Output,Allows program to use clrscr,getch,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <errno.h>//Including Error Number,def..integer variable errno,which number corresponds with an error,HEADER
/*-----------------------------------------------------------------------------------------------------------------*/
#include <time.h>//Including Time,defines the tm structure which records various members for time and *asctime,HEADER
/*struct tm {
   int tm_sec;         // seconds,  range 0 to 59          //
   int tm_min;         // minutes, range 0 to 59           //
   int tm_hour;        // hours, range 0 to 23             //
   int tm_mday;        // day of the month, range 1 to 31  //
   int tm_mon;         // month, range 0 to 11             //
   int tm_year;        // The number of years since 1900   //
   int tm_wday;        // day of the week, range 0 to 6    //
   int tm_yday;        // day in the year, range 0 to 365  //
   int tm_isdst;       // daylight saving time             //
};*/
/*-----------------------------------------------------------------------------------------------------------------*/
#define BUFFER_SIZE 1000//character array size defined for later on in the program,function del()
/*-----------------------------------------------------------------------------------------------------------------*/


/*-----------------------------------------------------------------------------------------------------------------*/
struct stock //data structure to save various information about item stock, used later on
{
    //members of the data structure
    char item[100]; //name of item
    int amount; //amount of the item available
    float cp; //cp=cost price, cost price of the item(how much the company paid for one unit of the item)
    float sp; //sp=selling price, selling price of the item(how much the companny is selling for one unit of the item)
}item_stock[1000]; //name of the structure variable
/*-----------------------------------------------------------------------------------------------------------------*/




/*-----------------------------------------------------------------------------------------------------------------*/
const /*declaring a constant character*/ char rocket[] =
"                                                           _\n\
                                                          /^\\\n\
                                                          |-|\n\
                                                          |W|\n\
                                                          |E|\n\
                                                          | |\n\
                                                          |P|\n\
                                                          |R|\n\
                                                         /|I|\\\n\
                                                        / |N| \\\n\
                                                       |  |T|  |\n\
                                                        `-\"\"\"-`\n\
";//We print logo for boot up
/*-----------------------------------------------------------------------------------------------------------------*/



/*-----------------------------------------------------------------------------------------------------------------*/
int main() //Main function

{
    for (int i = 0; i < 50; i ++) printf("\n"); // jump to bottom of console
     system("color 9F"); // changes console color.
     printf("%s", rocket); //prints the const char rocket
    int j = 300000; //determines how long the rocket takes to move up.
   for ( int i = 0; i < 50; i ++) {
        usleep(j); // move faster and faster,
       j = (int)(j * 0.9); // so sleep less each time
        printf("\n"); // move rocket a line upward
    }

    password();//Calls the  password function
    printMenu();//Calls the print menu function

} //End of Function
/*-----------------------------------------------------------------------------------------------------------------*/


/**
 * Function password(), asks the user for the password "252558" to continue to ensure that an authorized individual is using the program
 * as well as allowing the user to exit by entering "6"
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void password()
{
    system("color 1B");//Changes color of the console
    printf("\n");//Sends the pointer down one line
    char password[6];//Declares a character array password that holds six character addresses
    while(1) //a loop that repeats indefinitely  until broken by the break; statement
    {
        printf("Please enter the password to use this program or enter 6 to exit : \n"); //asks user to enter the password
        scanf("%s",password); //scans and inputs the value intered into the character array password
        if (strcmp(password,"6")==0) //compares the character array password to the character 6 and if it produces an output of 0 which is true it performs the following
        {  Sleep(2000); //delays the program by informing it to wait for the current thread by the specified amount of time inside the function sleep(x) where x is milliseconds
        system("cls"); //clears previous outputs printed out by the console.
        printf("Exiting in 3 seconds...\n"); // tells the user that the program is exiting in 3 seconds
        Sleep(3000); //delays for 3 seconds
        exit(1); //exit loop indefinitely
        }
        else //if the condition if (strcmp(password,"6")==0) is not true it will then perform this else if
        {
        if (strcmp(password,"252558")==0)           //password is 252558 //compares the character array password to the characters "2525558" and if it produces an output of 0 it performs the following
        {
            system("color 1A");
            system("cls"); 
            printf("Correct Password entered!\n"); 
            usleep(900000); //delays the program for 900000 microseconds
            system("cls"); 
            system("color 1C"); 
             printf("By Timothy Adams Fatima College Form 6"); 
             usleep(900000); 
             system("cls"); 
             system("color 1A"); 
              system("Pause"); //pauses the system until a keyboard input is detected
             break; //breaks function and returns to main and program performs other statements below it.
        }
        else         //incorrect password entered     //if above condition if (strcmp(password,"252558")==0 is not true then it can be assumed that the incorrect password is entered and will perform this
        {
             system("cls"); 
            printf("You have entered the wrong password! Please try again.\n"); 
             usleep(900000);
        }
    }
    system("cls"); //clears previous outputs printed by the console
} //while repeats until 6 or the correct password is entered.
} //End Of Function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function printMenu(), prints to the console a Graphical User Interface like menu,
 * to make selection of options much accesible and easier.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void printMenu()
{
    system("cls");

    system("color 1F");
    printf("\n");

    // Create Menu
    printf("\xB2 \xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2 We Print");//\xB2 is a special character that resembles a block.

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);//Console Color Handle
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE); //Defines the color of text (FOREGROUND) and background of menu (BACKGROUND) both use RED,BLUE,GREEN
           printf("|All In One System|");

    SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE); //There can be more than one FOREGROUND color these colors are mixed to produce one color, for eg red green blue makes white and that color is intensified using FOREGROUND_INTENSITY. same goes for BACKGROUND
    printf("\xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"
           "\xB2\xB2 \xB2");
    printf("\n ______________________________"
           "_________________________________");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t 1. ");
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
    printf("Inventory \t\t\t\t");
    SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("|");
    printf("\n|\t\t\t 2. Point Of ");
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|FOREGROUND_RED|BACKGROUND_BLUE);
    printf("Sale \t\t\t");
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("|");
    printf("\n|\t\t\t 3. View All");
     SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|FOREGROUND_RED|BACKGROUND_BLUE);
     printf(" Sales \t\t\t");
            SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("|");
    printf("\n|\t\t\t 4. ");
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE|FOREGROUND_INTENSITY);
    printf("Profit");
            SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf(" And ");
            SetConsoleTextAttribute(hConsole, FOREGROUND_RED|BACKGROUND_BLUE|FOREGROUND_INTENSITY);
    printf("Expenses \t\t");
             SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("|");
    printf("\n|\t\t\t 5. ");
    SetConsoleTextAttribute(hConsole, FOREGROUND_RED|BACKGROUND_BLUE);
    printf("Exit \t\t\t\t");
            SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n\xB2_________________________________"
           "______________________________\xB2\n");

    // Function call for select options
    selectMenu();
}//end of function
/*-----------------------------------------------------------------------------------------------------------------*/


/**
 * Function to take user choices and perform the appropriate operation
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void selectMenu()
{
    fcloseall; //closes any opened files by the program to prevent a memory leak exit status by the program.
    int choice; //intialise the integer choice
    printf("\n Enter your choice : "); //asks user to enter the choice
    scanf("%d", &choice); //scans the value entered and input it in the variable choice

    switch/*Switch statement allows the variable choice to be test against a lsit of values*/ (choice) {
    case 1: //if 1 is entered
        Inventory(); //Calls the Inventory Function
        break;

     case 2: //if 2 is entered
        pos(); //Calls the pos function, Point of Sale
        break;

    case 3: //if 3 is entered
        sale(); //Calls the sale function
        break;

     case 4: // if 4 is entered
        PnE(); //Calls the PnE Function, Profits and Expenses
        break;

     case 5: // if 5 is entered, exits program
        printf("\n Exiting... \n\n");
        printf("Exiting in 3 seconds...\n");
        Sleep(3000);
        exit(1);
        break;


    default: // if an unknown option is entered
        system("cls");
        printf("\ninvalid choice Try again \n");
        Sleep(3000);
        printMenu();//Calls the printMenu function
    }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function Inventory(), prints to the console a Graphical User Interface like menu,
 * to make selection of options specific to inventory of the company
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void Inventory()
{
    system("cls");
  system("color 1F");
    printf("\n");

    // Create Menu
    printf("\xB2 \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
           printf(" Inventory ");

    SetConsoleTextAttribute(hConsole,
    FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"
           "\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 \xB2");
    printf("\n ______________________________"
           "_________________________________");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t 1. View Inventory \t\t\t|");
    printf("\n|\t\t\t 2. Edit Inventory\t\t\t|");
    printf("\n|\t\t\t 3. Delete Stock \t\t\t|");
    printf("\n|\t\t\t 4. Return to Menu\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n|\t\t\t\t\t\t\t\t|");
    printf("\n\xB2_________________________________"
           "______________________________\xB2\n");

    check(); //Calls check function

}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function check(),creates countofstocks.txt and writes a 0 to it so that a value can be read later on
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void check()
{
    FILE*check=fopen("countofstocks.txt","r"); //initialises File pointer to check in read mode,if countofstocks.txt doesnt exist it is then created.
    if(check==NULL||check=="\0") //if check is equal to NULL(doesnt exist\empty) or if check is equal to \0(terminator) it will proceed with below
    {
        fclose(check); //closes the FILE pointer check
      FILE*intialise=fopen("countofstocks.txt","w"); // intialises FILE pointer to countofstocks.txt in write mode
      int num=0; //initialises and declares num as 0
      fprintf(intialise,"%d",num); //prints out num into the FILE pointer intialise which overwrites data in countofstocks.txt with 0 as a replace.
      fclose(intialise); //closes the FILE pointer check
      inventoryMenu(); //Calls the inventoryMenu function
    }
    else //else if the above condition isnt true its assumed there is a number in countofstocks.txt already
    {
     fclose(check); //closes the FILE pointer check
       inventoryMenu(); //Calls the inventoryMenu function
    }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/




/**
 * Function to take user choices and perform the appropriate operation
 */
/*-----------------------------------------------------------------------------------------------------------------*/
 void inventoryMenu()
 {
      fcloseall; //closes any opened files by the program to prevent a memory leak exit status by the program.
    int choice; //intialise the integer choice
    printf("\n Enter your choice : ");//asks user to enter the choice
    scanf("%d", &choice); //scans the value entered and input it in the variable choice

    switch/*Switch statement allows the variable choice to be test against a lsit of values*/ (choice) {
    case 1://if 1 is entered
        viewInventory();//Calls the viewInventory function
        break;

    case 2://if 2 is entered
       editInventory();//Calls the editInventory function
        break;

    case 3://if 3 is entered
       delInventory();//Calls the delInventory function
        break;


    case 4://if 4 is entered
        //Returns to menu
        printf("\n Returning... \n\n");
        printf("Returning in 3 seconds...\n");
        Sleep(3000);
        system("cls");
        printMenu(); //Calls the printMenu function


    default:// if an unknown option is entered
        system("cls");
        printf("\nInvalid choice Try again \n");
        system("pause");
        Inventory();//Calls the Inventory Function
    }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function viewInventory() reads the listofstocks.txt file and takes that name and searches for a file with that name
 * and prints out the data in that file, it is then repeated for the number of stock in the the list.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void viewInventory()
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
   FILE*count=fopen("countofstocks.txt","r");
   int i,max;
   char item[100];


  fscanf(count,"%d",&max);
  fclose(count);


 FILE*in=fopen("listofallstocks.txt","r");
 FILE*read;
  system("cls");

  if(in!=NULL)
  {
  for(i=0;i<max;i++)
  {
      fscanf(in,"%s",item_stock[i].item);
      read=fopen(item_stock[i].item,"r");
      printf("*");
       SetConsoleTextAttribute(hConsole,FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf("\n");
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN |FOREGROUND_BLUE|BACKGROUND_BLUE);
            printf("%s",item_stock[i].item);
            SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
            printf(" : ");
     fscanf(read,"%d ",&item_stock[i].amount);
      SetConsoleTextAttribute(hConsole,FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("%d",item_stock[i].amount);
    SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf(" Units Available, ");
      fscanf(read,"%f ",&item_stock[i].cp);
     printf("Costs $");
      SetConsoleTextAttribute(hConsole, FOREGROUND_RED|BACKGROUND_BLUE);
    printf("%0.2f",item_stock[i].cp);
     fscanf(read,"%f ",&item_stock[i].sp);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf(" Dollars,");
     printf(" and is sold for ");
     printf("$");
      SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
     printf("%0.2f",item_stock[i].sp);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf(" Dollars");
     printf("\n*");
  }
 fclose(in);
   printf("\nThese are currently all the stock in Inventory\n");
  fclose(read);
  system("\npause");
   printf("\nReturning...");
   Sleep(2000);
   Inventory();
  }
  else
    {
        fclose(in);
         fclose(count);
         fclose(read);
     printf("\nNo stock in the database, please add stocks using the Edit Inventory Option\n");
  system("\npause");
   printf("\nReturning...");
   Sleep(2000);
   Inventory();
    }

    if(max==0)
  {
    fclose(in);
         fclose(count);
         fclose(read);
     printf("\nNo stock in the database, please add stocks using the Edit Inventory Option\n");
  system("\npause");
   printf("\nReturning...");
   Sleep(2000);
   Inventory();
  }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function editInventory() prints out the available stock by opening the list of stocks file taking the name of the stock from listofstocks,
 * searches for a file name with that name and then scans in the data from that file.
 * countofstocks file which holds the total no. of stock gives the amount of time to repeat the function,
 * and prints out the data in that file, it is then repeated for x amount of time given from the countofstocks.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void editInventory()
{
      HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
      
    const int limit=5;
char *randstring(size_t); //intializing randomstring function
 char hold[100],*random;

  time_t t;
    srand((unsigned)time(&t)); //calling time for the random function

     int max,i;
    FILE*count=fopen("countofstocks.txt","r");
  fscanf(count,"%d",&max);
  fclose(count);
    FILE*in=fopen("listofallstocks.txt","r");
    FILE*read;

    printf("\nAll the stock found in the database are below\n");
    for(i=0;i<max;i++)
  {
      fscanf(in,"%s",item_stock[i].item);
      read=fopen(item_stock[i].item,"r");
      printf("*");
       SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf("\n");
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|BACKGROUND_BLUE);
            printf("%s",item_stock[i].item);
            SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
            printf(" : ");
     fscanf(read,"%d ",&item_stock[i].amount);
      SetConsoleTextAttribute(hConsole,FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("%d",item_stock[i].amount);
    SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf(" Units Available, ");
      fscanf(read,"%f ",&item_stock[i].cp);
     printf("Costs $");
      SetConsoleTextAttribute(hConsole, FOREGROUND_RED|BACKGROUND_BLUE);
    printf("%0.2f",item_stock[i].cp);
     fscanf(read,"%f ",&item_stock[i].sp);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf(" Dollars,");
     printf(" and is sold for ");
     printf("$");
      SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
     printf("%0.2f",item_stock[i].sp);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf(" Dollars");
     printf("\n*");
  }

    random=randstring(limit);//calling ranstring to create a random string, and intializing random with it.
    printf(" Enter the stock to edit(The Stock Must exist in the above list) \n");
    printf(" Or enter");
    SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|BACKGROUND_BLUE);
    printf(" %s ",random);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("to add a new stock \n");
    printf(" \n Enter stock name, an Invalid choice will cause the program to close : ");
    scanf("%s",hold);
    editInventory2(hold,random); //Passes the two variables to the editInventory2 function
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function editInventory compares a(hold) against b(random) to see if true and then performs the appropriate action
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void editInventory2(a/*hold*/,b/*random*/)
{
     if(strcmp(a,b)==0)//if the text entered is equal to the random string
        {
         iftrueinv(); //calls the iftrueinv function
        }
        else
        if(strcmp(a,b)!=0)//if the text entered is not equal to the random string
        {
        iffalseinv(a); //calls the iffalseinv function and passes through a(hold)
        }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * If a(hold),b(random) are the same string the program will then create a new file using the datastruct member item
 * and prints out user entered variables into the file such as amount,costprice,selling price, increments the count of stocks by 1
 * and calls Inventory()
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void iftrueinv()
{
      HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    int current,store;
         system("cls");
         FILE*data;
        FILE*count=fopen("countofstocks.txt","r");
        fscanf(count,"%d\n",&store);
        fclose(count);

        current=store+1;

        FILE*countout=fopen("countofstocks.txt","w");
        fprintf(countout,"%d\n",current);
        fclose(countout);


        printf("Enter the name of the new stock (no spaces): ");
        scanf("%s",item_stock[store].item);

        printf("\nThe Stock %s was successfully created\n",item_stock[store].item);
        printf("The original number of stocks %d is now %d.\n",store,current);

        printf("Enter the available amount for stock %s : ",item_stock[store].item);
        scanf("%d",&item_stock[store].amount);

      printf("\nEnter the cost price for stock %s : ",item_stock[store].item);
      scanf("%f",&item_stock[store].cp);
    SetConsoleTextAttribute(hConsole,FOREGROUND_GREEN|BACKGROUND_BLUE);
      printf("\n$%0.2f ",item_stock[store].cp);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("dollars paid for one unit of %s\n",item_stock[store].item);
       printf("\nEnter the selling price for stock %s : ",item_stock[store].item);
     scanf("%f",&item_stock[store].sp);
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
      printf("\n$%0.2f ",item_stock[store].sp);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf("dollars is the selling price for one unit of %s\n",item_stock[store].item);

     data=fopen(item_stock[store].item,"w");
     fprintf(data,"%d ",item_stock[store].amount);
     fprintf(data,"%0.2f ",item_stock[store].cp);
     fprintf(data,"%0.2f ",item_stock[store].sp);
     fclose(data);

     FILE*list=fopen("listofallstocks.txt","a");
     fprintf(list,"\n%s",item_stock[store].item);
     fclose(list);


     printf("\nData written successfully.");
     Sleep(3000);
     printf("\n Returning to menu....");
     Inventory();
}//End of file
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * If a(hold),b(random) are not the same string, the program will then search for a(random) in the listofstocks file and if found
 * it searches for a file with the name of a(random) and scans it in and prints it out, and allows the user to overwrite the values of the 
 * members of the data struct eg amount,cp,sp and prints it back out into the file. and then calls Inventory()
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void iffalseinv(a)
{
      HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
       FILE*count=fopen("countofstocks.txt","r");
       FILE*in=fopen("listofallstocks.txt","r");
       FILE*read;
      int i,i2,max;

      fscanf(count,"%d",&max);


      for(i=0;i<=max;i++)
      {
          fscanf(in,"%s",item_stock[i].item);
          FILE*read=fopen(item_stock[i].item,"r");
          fscanf(read,"%d ",&item_stock[i].amount);
           fscanf(read,"%f ",&item_stock[i].cp);
            fscanf(read,"%f ",&item_stock[i].sp);
    if(strcmp(a,item_stock[i].item)==0)
    {
        FILE*data;
     system("cls");
       printf("\nThe stock");
      SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf(" %s ",item_stock[i].item);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf("has");
      SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf(" %d ",item_stock[i].amount);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf("units, costs");
      SetConsoleTextAttribute(hConsole, FOREGROUND_RED|BACKGROUND_BLUE);
      printf(" %0.2f ",item_stock[i].cp);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf("dollars and is resold for");
      SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
      printf(" %0.2f ",item_stock[i].sp);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf("dollars");
     printf("\n If some values remain the same please re-enter the original value");

     printf("\nEnter the new amount of the stock %s : ",item_stock[i].item);
      scanf("%d",&item_stock[i].amount);
     printf("\n Enter the new cost price : ");
     scanf("%f",&item_stock[i].cp);
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
      printf("\n$%0.2f ",item_stock[i].cp);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
  printf("dollars paid for one unit of %s\n",item_stock[i].item);

     printf("\n Enter the new selling price : ");
     scanf("%f",&item_stock[i].sp);
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
      printf("\n$%0.2f ",item_stock[i].sp);
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("dollars is the selling price for one unit of %s\n",item_stock[i].item);
     printf("Editing Data for %s ",item_stock[i].item);




     FILE*edit=fopen(item_stock[i].item,"w");
     fprintf(edit,"%d ",item_stock[i].amount);
     fprintf(edit,"%0.2f ",item_stock[i].cp);
     fprintf(edit,"%0.2f ",item_stock[i].sp);
     fclose(edit);

     printf("\n Data edited and saved");
     printf("\nReturning to menu\n");
     system("pause");
     Inventory();


     i2=60;
 }
  }

  if(i2!=60);
  {
       fclose(read);
        fclose(count);
     fclose(in);
        system("cls");
        system("color 1C");
        printf("Cannot open FILE \n");
        Sleep(1000);
        system("pause");
        system("cls");
        system("color 1F");
        Inventory();
   }
         fclose(read);
         fclose(count);
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Prints out all the stock, in the inventory and then asks the user which one they would want to delete.
 * program then takes this and passes it to the del(stock) function
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void delInventory()
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    system("cls");

    int max,i;
    FILE*count=fopen("countofstocks.txt","r");
  fscanf(count,"%d",&max);
  fclose(count);
    FILE*in=fopen("listofallstocks.txt","r");
    FILE*read;

    if(in!=NULL)
  {
  for(i=0;i<max;i++)
  {
      fscanf(in,"%s",item_stock[i].item);
      read=fopen(item_stock[i].item,"r");
      printf("*");
       SetConsoleTextAttribute(hConsole,FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf("\n");
      SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN |FOREGROUND_BLUE|BACKGROUND_BLUE);
            printf("%s",item_stock[i].item);
            SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
            printf(" : ");
     fscanf(read,"%d ",&item_stock[i].amount);
      SetConsoleTextAttribute(hConsole,FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("%d",item_stock[i].amount);
    SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
      printf(" Units Available, ");
      fscanf(read,"%f ",&item_stock[i].cp);
     printf("Costs $");
      SetConsoleTextAttribute(hConsole, FOREGROUND_RED|BACKGROUND_BLUE);
    printf("%0.2f",item_stock[i].cp);
     fscanf(read,"%f ",&item_stock[i].sp);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf(" Dollars,");
     printf(" and is sold for ");
     printf("$");
      SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|BACKGROUND_BLUE);
     printf("%0.2f",item_stock[i].sp);
     SetConsoleTextAttribute(hConsole,FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
     printf(" Dollars");
     printf("\n*");
  }
 fclose(in);
   printf("\nThese are currently all the stock in Inventory\n");
  fclose(read);
  }
    char stock[200];

    printf("Please enter the stock to delete : ");
    scanf("%s",stock);
    printf("%s entered, searching for file.",stock);
    del(stock);
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/

/**
 * Asks user to confirm and then deletes the file, else prints and error according to errorno's status.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void del(stock)
{
     HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    const int limit=5;
char *randstring(size_t);
 char hold[100],*random;

  time_t t;
    srand((unsigned)time(&t));
     random=randstring(limit);
    printf("\nTo confirm that you are sure about deleting the file, please type");
    SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|BACKGROUND_BLUE);
        printf(" %s ",random);
    SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY|BACKGROUND_BLUE);
    printf("\nOr enter x to exit : ");
    scanf("%s",hold);
    if(strcmp(hold,random)==0)
    {
     if(remove(stock)==0)
 {
    printf("\nFile Successfully Deleted\n");
    system("pause");
    updatelist(stock);
    }
    else
   {
    printf("\nFile was not deleted.\n");
    if(errno==1)
    {
     printf("\nOperation not permitted\n");
    }
    else
     if(errno==2)
    {
      printf("\nNo such file or directory\n");
    }
    else
     if(errno==3)
    {
      printf("\nNo such process\n");
    }
    else
     if(errno==4)
    {
      printf("\nInterrupted system call\n");
    }
    else
     if(errno==5)
    {
     printf("\nI/O error\n");
    }
    else
     if(errno==6)
    {
      printf("\nNo such device or address\n");
    }
    else
     if(errno==7)
    {
      printf("\nArgument list too long\n");
    }
    else
     if(errno==8)
    {
       printf("\nExec format error\n");
    }
    else
     if(errno==9)
    {
      printf("\nBad file number\n");
    }
    else
     if(errno==10)
    {
       printf("\nNo child processes\n");
    }
    else
     if(errno==11)
    {
      printf("\nTry again\n");
    }
    else
     if(errno==12)
    {
      printf("\nOut of memory\n");
    }
    else
     if(errno==13)
    {
       printf("\nPermission denied, Try running the exe of this build as administrator\n");
    }
    system("pause");
    printMenu();
   }
   }
   else
   {
       printf("\nOperation Cancelled");
       printf("\nExiting to menu\n");
       system("pause");
       Inventory();
   }
    }//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Remove all occurences of the filename from the list of stocks, and decreases the count of stocks by 1.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void updatelist(a)
{
    FILE*fPtr;
    FILE*fTemp;
    char path[21];

    char toRemove[100];
    char buffer[1000];

    strcpy(path,"listofallstocks.txt");
   strcpy(toRemove,a);
    printf("\nReading the stock list '%s' and looking for the stock %s",path,toRemove);





    /*  Open files */
    fPtr  = fopen(path, "r");
    fTemp = fopen("delete.tmp", "w");

    /* fopen() return NULL if unable to open file in given mode. */
    if (fPtr == NULL || fTemp == NULL)
    {
        /* Unable to open file hence exit */
        printf("\nUnable to stock file.\n");
        printf("Please check whether file exists and you have read/write privilege.\n");
        exit(EXIT_SUCCESS);
    }


    /*
     * Read line from source file and write to destination
     * file after removing given word.
     */
    while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
    {
        // Remove all occurrence of word from current line
        removeAll(buffer,toRemove);

        // Write to temp file
        fputs(buffer, fTemp);
    }


    /* Close all files to release resource */
    fclose(fPtr);
    fclose(fTemp);


    /* Delete original source file */
    remove(path);

    /* Rename temp file as original file */
    rename("delete.tmp", path);


    printf("\nAll occurrence of '%s' removed successfully.", toRemove);
       FILE*count=fopen("countofstocks.txt","r");
       int max;
      fscanf(count,"%d",&max);
      fclose(count);
      FILE*countout=fopen("countofstocks.txt","w");
      int current;
      current=max-1;
      printf("\nThe original number of stock %d, is now %d\n",max,current);
      fprintf(countout,"%d",current);
      fclose(countout);
      system("pause");
       printMenu();
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/


/**
 * Function to Remove all occurrences of a given word in string.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void removeAll(char * str, const char * toRemove)
{
    int i, j, stringLen, toRemoveLen;
    int found;

    stringLen= strlen(str);      // Length of string
    toRemoveLen=strlen(toRemove); // Length of word to remove


    for(i=0; i <= stringLen - toRemoveLen; i++)
    {
        /* Match word with string */
        found = 1;
        for(j=0; j < toRemoveLen; j++)
        {
            if(str[i + j] != toRemove[j])
            {
                found = 0;
                break;
            }
        }

        /* If it is not a word */
        if(str[i + j] != ' ' && str[i + j] != '\t' && str[i + j] != '\n' && str[i + j] != '\0')
        {
            found = 0;
        }

        /*
         * If word is found then shift all characters to left
         * and decrement the string length
         */
        if(found == 1)
        {
            for(j=i; j <= stringLen - toRemoveLen; j++)
            {
                str[j] = str[j + toRemoveLen];
            }

            stringLen = stringLen - toRemoveLen;

            //match next occurrence of word from current index.
            i--;
        }
    }
}
/*-----------------------------------------------------------------------------------------------------------------*/


/**
 * Function to Randomize a string of characters.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
char *randstring(size_t length) {

    static char charset[] = "abcdefghijklmnopqrstuvwxyz0123456789";
    char *randomString = NULL;

    if (length)
        {
            randomString=malloc(sizeof(char)*(length +1));


        if (randomString)
            {
            for (int n = 0;n<length;n++)
                {
                int key = rand()%(36-1);
                randomString[n] = charset[key];
            }
        }
    }

    return (char *)randomString;
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Point of sale function of the program acts like a cash register, asks user to enter the item, and the amount being purchased
 * returns the total price and then asks for the amount the customer has given and returns the amount of change to give if the amount paid
 * is more than the price,then saves this and the time of transaction to the transaction file to be read in another function.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
 void pos()
{
 startfiles();
 printf("------------------------------------------------------------");
  FILE*count=fopen("countofstocks.txt","r");
   int i,id,max,limit,total,amount;
  float n,change;
   char item[100];


  fscanf(count,"%d",&max);

 FILE*in=fopen("listofallstocks.txt","r");
 FILE*read;
 FILE*current=fopen("ongoingtransaction.txt","w");
 fprintf(current,"\0");

  system("cls");

  if(in!=NULL)
  {
  printf("all the available stock are below");
  for(i=0;i<max;i++)
  {
      fscanf(in,"%s",item_stock[i].item);
      read=fopen(item_stock[i].item,"r");
      printf(" ");
     printf("\n%s: ",item_stock[i].item);
      fscanf(read,"%d ",&item_stock[i].amount);
     printf("Units:%d ",item_stock[i].amount);
      fscanf(read,"%f ",&item_stock[i].cp);
     printf("Cost: $%0.2f ",item_stock[i].cp);
     fscanf(read,"%f ",&item_stock[i].sp);
     printf("Selling Price: $%0.2f \t",item_stock[i].sp);
     printf("\n");
  }

    printf("\nPlease enter how much times to repeat the purchase function, for each stock being purchased\nor -9 to exit : ");
    scanf("%d",&limit);
       if(limit==-9)
    {
      printf("\nExiting to Menu");
      printf("\nprocess cancelled\n");
      system("pause");
      Inventory();
    }
    else
    if(limit==1)
    {
    printf("\nOne entered...");
      printf("\nThis process will only happen once\n");
    system("pause");
    }
    else
        if(limit<=0)
    {

        do
        {
            printf("\nInvalid number, please enter a valid number starting from 1");
           printf("\nPlease enter how much times to repeat the purchase function, for each stock being purchased : ");
           scanf("%d",&limit);
        }
        while(limit<1);
    }
    else
        if(limit>1)
    {
            printf("This process will be repeated %d times\n",limit);
    system("pause");
    }


    for(int i2=1;i2<=limit;i2++)
    {
        system("cls");
        printf("all the available stock are below");
  for(int i4=0;i4<max;i4++)
  {
      fscanf(in,"%s",item_stock[i4].item);
      read=fopen(item_stock[i4].item,"r");
      printf(" ");
     printf("\n%s: ",item_stock[i4].item);
      fscanf(read,"%d ",&item_stock[i4].amount);
     printf("Units:%d ",item_stock[i4].amount);
      fscanf(read,"%f ",&item_stock[i4].cp);
     printf("Cost: $%0.2f ",item_stock[i4].cp);
     fscanf(read,"%f ",&item_stock[i4].sp);
     printf("Selling Price: $%0.2f \t",item_stock[i4].sp);
     printf("\n");
  }

int ch;
  printf("Enter the item : ");
  scanf("%s",item);
  for(i=0;i<max;i++)
  {
    if(strcmp(item,item_stock[i].item)==0)
    {
     printf("\nItem found!");
     if(item_stock[i].amount<=0)
     {
         printf("Sorry There is no available amount in this stock.");
         system("pause");
         printMenu();
     }
     printf("\nEnter the quantity being purchased : ");
     scanf("%d",&amount);
     id=i;
     if(amount>item_stock[i].amount)
     {
        do
        {
        printf("This amount is more than the available amount");
        printf(" Enter a valid amount : ");
     scanf("%d",&amount);
        } while(amount>item_stock[i].amount);
     }
     printf("\nTotal for %s is : %d units X %0.2f dollars",item_stock[i].item,amount,item_stock[i].sp);
     n=item_stock[i].sp*amount;
     printf("\nItem : %s | Quantity : %d | Price : $%0.2f each | Total : $%0.2f dollars\n",item_stock[i].item,amount,item_stock[i].sp,n);
     fclose(current);
     FILE*current2=fopen("ongoingtransaction.txt","w");
    fprintf(current2,"\nItem : %s | Quantity : %d | Price : $%0.2f each | Total : $%0.2f dollars",item_stock[i].item,amount,item_stock[i].sp,n);
     fclose(current2);
     system("pause");
      ch=60;
    }
    else
        if(ch!=60)
    {
        printf("Invalid Entry, Item does not exist\n");
        system("pause");
        printMenu();
    }
  }


     FILE*current2=fopen("ongoingtransaction.txt","a");
    fprintf(current2,"\n-----------------\n%0.2f",n);
    FILE*current3=fopen("ongoingtransaction.txt","r");
     char s;
      while((s=fgetc(current3))!=EOF) {
      printf("%c",s);
      }
      float payment;
      printf("\nEnter the amount of money the customer has given : ");
      scanf("%f",&payment);
      change=payment-n;
      if(change<0)
      {
          float remain;
          change=n-payment;
         printf("The customer is owing $%0.2f dollars\n",change);
          system("pause");
           printf("\nEnter the remaining amount the customer has given : ");
           scanf("%f",&remain);
           change=remain-change;
      }
int LEN=150;
char buf[LEN];
   time_t curtime;
   struct tm *loc_time;

   //Getting current time of system
   curtime = time (NULL);

   // Converting current time to local time
   loc_time = localtime (&curtime);


      FILE*lastprocess=fopen("lasttransaction.txt","w");

      if(change>0)
      {
          FILE*sales=fopen("totalsales.txt","a");

          printf("Please give the customer $%0.2f dollars change",change);
           printf("\nTransaction Saved");
          fprintf(sales,"\nItem : %s | Quantity : %d | Price : $%0.2f each | Total : $%0.2f | Payment : $%0.2f  | Change : $%0.2f  ",item_stock[id].item,amount,item_stock[id].sp,n,payment,change);
          fprintf(sales,"\nProcessed at : %s\n----------------------------------", asctime (loc_time));
          fprintf(lastprocess,"\n%s\n", asctime (loc_time));
         fclose(lastprocess);
          fclose(sales);
          printf("\nItem : %s | Quantity : %d | Price : $%0.2f each | Total : $%0.2f | Payment : $%0.2f | Change : $%0.2f  ",item_stock[id].item,amount,item_stock[id].sp,n,payment,change);
          printf("\nProcessed at : %s", asctime (loc_time));
            FILE*expensesr=fopen("expenses.txt","r");
     float expenses;
     FILE*profitsr=fopen("profits.txt","r");
     float profits;
     FILE*totalr=fopen("payments.txt","r");
     float paymenttotal;
      fscanf(totalr,"%f",&paymenttotal);
     fscanf(expensesr,"%f",&expenses);
     fscanf(profitsr,"%f",&profits);
     fclose(expensesr);
     fclose(profitsr);
     fclose(totalr);
     paymenttotal=paymenttotal+n;
     expenses=expenses+(item_stock[id].cp*amount);
     profits=profits+(n-expenses);
     FILE*expensesw=fopen("expenses.txt","w");
      fprintf(expensesw,"%0.2f",expenses);
     FILE*profitsw=fopen("profits.txt","w");
     fprintf(profitsw,"%0.2f",profits);
      FILE*totalw=fopen("payments.txt","w");
       fprintf(totalw,"%0.2f",paymenttotal);
     fclose(expensesw);
     fclose(profitsw);
     fclose(totalw);
          system("pause");
          system("cls");
           item_stock[id].amount=item_stock[id].amount-amount;
      printf("%d units of %s left\n",item_stock[id].amount,item_stock[id].item);
    FILE*data=fopen(item_stock[id].item,"w");
     fprintf(data,"%d ",item_stock[id].amount);
     fprintf(data,"%0.2f ",item_stock[id].cp);
     fprintf(data,"%0.2f ",item_stock[id].sp);
     fclose(data);
         system("pause");
      }

        if(change==0)
      {
          FILE*sales=fopen("totalsales.txt","a");

          printf("\nTransaction Saved");
          fprintf(sales,"\nItem : %s | Quantity : %d | Price : $%0.2f each | Total : $%0.2f | Payment : $%0.2f  | Change : $%0.2f  ",item_stock[id].item,amount,item_stock[id].sp,n,payment,change);
          fprintf(sales,"\nProcessed at : %s\n----------------------------------", asctime (loc_time));
           fprintf(lastprocess,"\n%s\n", asctime (loc_time));
          fclose(sales);
          fclose(lastprocess);
          printf("\nItem : %s | Quantity : %d | Price : $%0.2f each | Total : $%0.2f | Payment : $%0.2f  | Change : $%0.2f ",item_stock[id].item,amount,item_stock[id].sp,n,payment,change);
           printf("\nProcessed at : %s", asctime (loc_time));
           system("pause");
             system("cls");
                FILE*expensesr=fopen("expenses.txt","r");
     float expenses;
     FILE*profitsr=fopen("profits.txt","r");
     float profits;
     FILE*totalr=fopen("payments.txt","r");
     float paymenttotal;
      fscanf(totalr,"%f",&paymenttotal);
     fscanf(expensesr,"%f",&expenses);
     fscanf(profitsr,"%f",&profits);
     fclose(expensesr);
     fclose(profitsr);
     fclose(totalr);
     paymenttotal=paymenttotal+n;
     expenses=expenses+(item_stock[id].cp*amount);
     profits=profits+(n-expenses);
     FILE*expensesw=fopen("expenses.txt","w");
      fprintf(expensesw,"%0.2f",expenses);
     FILE*profitsw=fopen("profits.txt","w");
     fprintf(profitsw,"%0.2f",profits);
      FILE*totalw=fopen("payments.txt","w");
       fprintf(totalw,"%0.2f",paymenttotal);
     fclose(expensesw);
     fclose(profitsw);
     fclose(totalw);
     system("pause");
              system("cls");
           item_stock[id].amount=item_stock[id].amount-amount;

      printf("%d units of %s left\n",item_stock[id].amount,item_stock[id].item);
    FILE*data=fopen(item_stock[id].item,"w");
     fprintf(data,"%d ",item_stock[id].amount);
     fprintf(data,"%0.2f ",item_stock[id].cp);
     fprintf(data,"%0.2f ",item_stock[id].sp);
     fclose(data);
          system("pause");
      }
    }
    sale();

}
    else
     {
       system("cls");
       printf("\nNo Stocks in database\n");
       system("pause");
       printMenu();
     }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function to ensure that all the files related to the pos() function that includes a number are initialised with 0
 * to ensure a number is in it to be read
 */
/*-----------------------------------------------------------------------------------------------------------------*/
void startfiles()
{
      FILE*check=fopen("expenses.txt","r");
    if(check==NULL||check=="\0")
    {
      FILE*intialise=fopen("expenses.txt","w");
      int num=0;
      fprintf(intialise,"%d",num);
      fclose(check);
      fclose(intialise);
    }

      FILE*check1=fopen("profits.txt","r");
    if(check1==NULL||check1=="\0")
    {
      FILE*intialise=fopen("profits.txt","w");
      int num=0;
      fprintf(intialise,"%d",num);
      fclose(check1);
      fclose(intialise);
    }

      FILE*check2=fopen("payments.txt","r");
    if(check2==NULL||check2=="\0")
    {
      FILE*intialise=fopen("payments.txt","w");
      int num=0;
      fprintf(intialise,"%d",num);
      fclose(check2);
      fclose(intialise);
    }
}//End of function
/*-----------------------------------------------------------------------------------------------------------------*/



/**
 * Function to print out the transaction file that shows all the transactins that occured.
 */
/*-----------------------------------------------------------------------------------------------------------------*/
 void sale()
 {
      FILE*lastprocess=fopen("lasttransaction.txt","r");
         FILE*current3=fopen("totalsales.txt","r");
     system("cls");
     if((lastprocess!=NULL)&&(current3!=NULL))
     {
     printf("\xB2\xB2\xB2\xB2Sales\xB2\xB2\xB2\xB2\n");
     printf("Last Transaction was at : \n");
     char s;
      while((s=fgetc(lastprocess))!=EOF) {
      printf("%c",s);
      }
      printf("\n----------------------------------\n");

      while((s=fgetc(current3))!=EOF) {
      printf("%c",s);
      }
      system("pause");
      printMenu();
     }
     else
     {
       system("cls");
       printf("\nNo Stocks in database\n");
       system("pause");
       printMenu();
     }
 }//End of function
 /*-----------------------------------------------------------------------------------------------------------------*/

 
 
 /**
 * Function to print out the total income,expenses and prints out whether if it is a profit or a loss
 */
/*-----------------------------------------------------------------------------------------------------------------*/
 void PnE()
 {
      FILE*expenses=fopen("expenses.txt","r");
       FILE*lastprocess=fopen("lasttransaction.txt","r");
        FILE*total=fopen("payments.txt","r");
         FILE*profits=fopen("profits.txt","r");
     if((expenses!=NULL)&&(lastprocess!=NULL)&&(total!=NULL)&&(profits!=NULL))
     {
     system("cls");
      system("color 3F");

     float expenses1;
     fscanf(expenses,"0.2f",expenses1);
      char s;
      printf("After the last transaction at : ");

       while((s=fgetc(lastprocess))!=EOF) {
      printf("%c",s);
      }
      printf("\nThe business's expenses ran a total of : ");
      printf("$");
      while((s=fgetc(expenses))!=EOF) {
      printf("%c",s);
      }
      printf(" dollars");



         printf("\nWith a total income of : ");
      printf("$");
      while((s=fgetc(total))!=EOF) {
      printf("%c",s);
      }
      printf(" dollars");




      float profits1;
      fscanf(profits,"0.2f",profits1);

      if(expenses1>profits1)
      {
          int expenses2;
          expenses2=(profits1-expenses1);
          printf("\nUnfortunately suffering a debt of %0.2f",expenses2);
          printf("\nDue to the profit income of");
             printf("$");
      while((s=fgetc(profits))!=EOF) {
      printf("%c",s);
      }
      printf(" dollars");
      system("pause");
       printMenu();
      }
      else
      {
             printf("\nMaking a profit income of : ");
             printf("$");
      while((s=fgetc(profits))!=EOF) {
      printf("%c",s);
      }
      printf(" dollars\n");
      }
      system("pause");
      printMenu();
     }
     else
     {
       system("cls");
       printf("\nNo Stocks in database\n");
       system("pause");
       printMenu();
     }
 }//End of function
/*-----------------------------------------------------------------------------------------------------------------*/


                                          /*███████ ███    ██ ██████      ██████   ███████     ███████ ██ ██      ███████ 
                                            ██      ████   ██ ██   ██     ██    ██ ██          ██      ██ ██      ██      
                                            █████   ██ ██  ██ ██   ██     ██    ██ █████       █████   ██ ██      █████   
                                            ██      ██  ██ ██ ██   ██     ██    ██ ██          ██      ██ ██      ██      
                                            ███████ ██   ████ ██████       ██████  ██          ██      ██ ███████ ███████ 
                                                                                                                         */
\$\endgroup\$
5
  • 3
    \$\begingroup\$ I think you'd benefit from developing with a rather high warning level turned on when compiling. The compiler gives a lot of support. /W4 - to make it warn about just anything (nasty mode). /permissive- - turn off things the Microsoft compiler (if that's what you're using) will allow, but that are not mandated by the standard to be working. Eradicating all warnings/errors with those two options activated will lead you to a program with a lot less bugs. Your program is currently riddled with things that may make your program behave in strange ways. \$\endgroup\$
    – Ted Lyngmo
    Jan 5 at 23:25
  • \$\begingroup\$ @TedLyngmo My compiler which is codeblocks permits me to run the program and i currently am not seeing warnings ill fix that and will do my best to eradicate any warnings... thank you \$\endgroup\$ Jan 6 at 0:15
  • 2
    \$\begingroup\$ Ok, codeblocks uses the mingw toolset for windows? If so, add the compiler options -Wall -Wextra -Werror -pedantic-errors \$\endgroup\$
    – Ted Lyngmo
    Jan 6 at 0:16
  • \$\begingroup\$ @TedLyngmo okay my program compiler is warning me now, and doesnt build... wow 54 errors from what i see its just confilicting types for my functions when i call them and implicit declaration... how may I fix this if thats something you can answer and if its no problem to you \$\endgroup\$ Jan 6 at 0:35
  • 2
    \$\begingroup\$ I'm afraid you'll have to look at each warning and error and figure out what it means. Fortunately, most of the issues in your program are very similar so when you've fixed one or two, you'll notice a pattern and then you'll get through the rest very quickly. Note: I added the -Werror option to turn warnings into hard errors. If you remove that option, the compiler will let you through with warnings, but - that is not a good way to start. The warnings are really really helpful, so fix them and your code will usually be more robust. \$\endgroup\$
    – Ted Lyngmo
    Jan 6 at 0:40
3
\$\begingroup\$

Remove unnecessary comments

You have added a lot of comments to your code, most of them are however unnecessary. For example, why is there a huge banner saying "START OF FILE" at the start of the file? It states the obvious, but takes up valuable space. Just remove it.

Explaining the C language in comments is not helpful. Maybe if you are an absolute beginner might it help seeing code annotated in this way, but for anyone else, including yourself if you've become a bit more comfortable, it again is just stating obvious things. Information like this can be found in any book or tutorial about C, you shouldn't copy it into your own programs.

Rather keep comments to a minimum, only using them to explain non-obvious things.

Avoid calling system()

Every time you call system(), a new cmd.exe process is created which then has to parse the command you pass it, and depending on the command maybe other processes are created. This is hugely inefficient, as well as non-portable (for example, cls only works on Windows, on UNIX-like operating systems you would need to use clear).

There are various ways to avoid system() in your program. The simplest is to just avoid all the fancy colors and screen clearing. Another would be to use the console functions like SetConsoleTextAttribute(). You can read the documentation Microsoft provides, it even has a section of how to clear the screen. However, this still is Windows-specific. To get even more features and at the same time be more portable, you could consider using a curses library.

Avoid sleeping arbitrarily

Calling Sleep(3000) will force an exact 3 second pause of the program. Maybe it is just enough for the user to see something before you then clear the screen, but maybe they were just looking somewhere else and missed it. Or they want to just have the program continue quickly, but the arbitrary pauses make it feel very sluggish.

If you don't clear the screen all the time, you also don't need the pauses. Alternatively, instead of sleeping an arbitrary amount of time, wait for the user to press a key to continue. They can then control how fast things go.

I/O error checking

There are several issues with how you handle files. First of all, this line doesn't do anything:

fcloseall;

You need to write fcloseall() (with the parentheses) in order to call this function. But you normally should never need to use fcloseall(), instead you should be able to properly fclose() any file you fopen()ed.

If fopen() returns NULL, then calling fclose() on the NULL-pointer is not valid, and will likely cause your program to crash.

Furthermore, I/O errors can occur at any time, not just when opening a file. Think of bad sectors on your disk, or trying to write when there is no more room on the disk, or you are reading/writing from a USB stick that is being removed. You should check the return value of all I/O functions, and then also handle any errors in a meaningful way: first, print an error message to stderr, so the user knows something is wrong, and then either exit(1) or abort() the program if you cannot continue running the program correctly anymore, or do something else to avoid reading/writing incorrect data.

Free memory that you allocate

I see a call to malloc(), but no calls to free() in your code. That means you are leaking memory. Ensure every time you allocate memory, it is freed when that memory is no longer used.

\$\endgroup\$
1
  • \$\begingroup\$ this is very great advice, i was aware that i might have over commented but for the sake of posting this here i thought i would have made it easier for users like yourself to read, my apologies. Thank you! \$\endgroup\$ Jan 6 at 2:32
1
\$\begingroup\$

Use an auto-formatter

Bugs: string

Never use scanf("%s",...); without a width limit like scanf("%5s",password);. The width must be less than the array count.

char password[6];
...
    scanf("%s",password);
    ...
    if (strcmp(password,"252558")==0)

For strcmp(password,"252558")==0 to be true, more than 5 characters must have been entered, which is a buffer overrun and undefined behavior (UB).

Instead, account for the null character of a string and don't be stingy on size.

char password[100];
...
    scanf("%99s",password);
    ... 
    if (strcmp(password,"252558")==0)

Bug: Too narrow

fgetc() returns an int in the unsinged char range or EOF (some negative value). When char is as unsigned char, (s=fgetc(expenses))!=EOF is never true. Use int s;.

// char s;
int s;
...
while((s=fgetc(expenses))!=EOF) {

Bug: No % specifier

  float profits1;
  // fscanf(profits,"0.2f",profits1);
  fscanf(profits, "%f", &profits1);
  //               ^    ^ 

Bugs: FILE *

Comparing a FILE pointer to some string literal pointer "\0" makes no sense.

Comparing a FILE pointer to NULL make sense, but then calling fclose(NULL) leads to more UB.

//FILE*check=fopen("countofstocks.txt","r");
//if(check==NULL||check=="\0") {
//    fclose(check); //closes the FILE pointer check

Instead do not fclose(check) when check == NULL.

FILE*check=fopen("countofstocks.txt","r");
if (check==NULL) {
  // fclose(check);
  ....

Bug: non-call

In void inventoryMenu(), simply state the function name: fcloseall; does nothing.

Certainly OP meant fcloseall();

Run spell check on comments


Too many issues for now.

\$\endgroup\$
2
  • \$\begingroup\$ I apologize about my issues. Thank you for giving me your input and advice, I am now learning a lot about c and my common mistakes. also my spelling is due to me not being a native speaker sorry \$\endgroup\$ Jan 8 at 0:16
  • \$\begingroup\$ @HelperShoes Minor issue: Find a spell checker. I use one too even though I am a native English speaker. \$\endgroup\$ Jan 8 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.