How to write to a binary file in C Programming

/*
* Program to write to a binary file
* From the book:
*
* This program writes fifty random numbers 
* (between 0 and 99) to a binary file.
*/

#include <stdio.h>
#include <stdlib.h> // For rand() and srand()
#include <time.h> // For time(), used with srand()

/*
* Set the file path and name as a C preprocessor macro.
* .dat is the three letter extension representing data.
*/

#define THEFILE "numbers.dat" 

/*
* Create a constant macro representing the number of 
* items in the array. 
*/

#define ITEMS 50

/*
* Begin the main function and create file pointer.
*/

int main (void) {

/*
* Need a pointer of type FILE.
*/

FILE *fp;

/*
* Loop counter.
*/

int i;

/*
* Array in which random numbers will be stored.
*/

int numbers[ITEMS];

/*
* Attempt to open the file for binary writing.
* This call opens the file for writing, creating
* the file if it doesn't exist, and wiping out
* any existing data. The binary mode is indicated
* by adding the b. This is only required on Windows.
*/

fp = fopen(THEFILE, "wb");

/*
* The file is open. Start a conditional based on 
* the file pointer. 
*/

if (fp != NULL) {

/*
* Seed the rand() function.
*/

srand((unsigned)time(NULL));

/*
* Populate the array with random numbers 
* less than 100. The for loop counts from
i to ITEMS, the number of elements in the
* array. Within the loop, each element is 
* assigned a random value between 0 and 99.
* This limit is accomplished by assigning 
* the remainder of dividing by the random 
* number by 100, rather than assigning the
* random number itself (which could be as 
* high as 32,767).
*/

for (i = 0; i < ITEMS; i++) {
numbers[i] = rand() % 100;

}

/*
* Write the array elements to the 
* binary file and print a message to
* the user. The fwrite() line starts
* by using the numbers variable as its
* pointer. This works because an array
* name is equivalent to its address in C.
* The function is then told to write ITEMS
* number of blocks, each of which is
* sizeof(int) bytes in size. We use 
* sizeof(int) because numbers is an array
* of integers.
*/

fwrite (numbers, sizeof(int), ITEMS, fp);

printf("The data has been written.\n");

} else {

printf("The file cound not be opened. \n");

/*
* Exit the function/application.
*/

return 1;

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {
printf("The file could not be closed.\n");
}

/*
* Pause.
*/
getchar();

return 0;
}

Python Game: Mad Lib

# Mad Lib
# Create a story based on user input
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI application that creates a story based on user input. """
    def __init__(self, master):
        """ Initialize Frame. """
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create widgets to get story information and to display story. """
        # create instruction label
        Label(self,
              text = "Enter information for a new story"
              ).grid(row = 0, column = 0, columnspan = 2, sticky = W)

        # create a label and text entry for the name of a person
        Label(self,
              text = "Person: "
              ).grid(row = 1, column = 0, sticky = W)
        self.person_ent = Entry(self)
        self.person_ent.grid(row = 1, column = 1, sticky = W)

        # create a label and text entry for a plural noun
        Label(self,
              text = "Plural Noun:"
              ).grid(row = 2, column = 0, sticky = W)
        self.noun_ent = Entry(self)
        self.noun_ent.grid(row = 2, column = 1, sticky = W)

        # create a label and text entry for a verb
        Label(self,
              text = "Verb:"
              ).grid(row = 3, column = 0, sticky = W)
        self.verb_ent = Entry(self)
        self.verb_ent.grid(row = 3, column = 1, sticky = W)
     
        # create a label for adjectives check buttons
        Label(self,
              text = "Adjective(s):"
              ).grid(row = 4, column = 0, sticky = W)

        # create itchy check button
        self.is_itchy = BooleanVar()
        Checkbutton(self,
                    text = "itchy",
                    variable = self.is_itchy
                    ).grid(row = 4, column = 1, sticky = W)

        # create joyous check button
        self.is_joyous = BooleanVar()
        Checkbutton(self,
                    text = "joyous",
                    variable = self.is_joyous
                    ).grid(row = 4, column = 2, sticky = W)

        # create electric check button
        self.is_electric = BooleanVar()
        Checkbutton(self,
                    text = "electric",
                    variable = self.is_electric
                    ).grid(row = 4, column = 3, sticky = W)

        # create a label for body parts radio buttons
        Label(self,
              text = "Body Part:"
              ).grid(row = 5, column = 0, sticky = W)

        # create variable for single, body part
        self.body_part = StringVar()
  
        # create body part radio buttons
        body_parts = ["bellybutton", "big toe", "medulla oblongata"]
        column = 1
        for part in body_parts:
            Radiobutton(self,
                        text = part,
                        variable = self.body_part,
                        value = part
                        ).grid(row = 5, column = column, sticky = W)
            column += 1

        # create a submit button
        Button(self,
               text = "Click for story",
               command = self.tell_story
               ).grid(row = 6, column = 0, sticky = W)

        self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
        self.story_txt.grid(row = 7, column = 0, columnspan = 4)

    def tell_story(self):
        """ Fill text box with new story based on user input. """
        # get values from the GUI
        person = self.person_ent.get()
        noun = self.noun_ent.get()
        verb = self.verb_ent.get()
        adjectives = ""
        if self.is_itchy.get():
            adjectives += "itchy, "
        if self.is_joyous.get():
            adjectives += "joyous, "
        if self.is_electric.get():
            adjectives += "electric, "
        body_part = self.body_part.get()

        # create the story
        story = "The famous explorer "
        story += person
        story += " had nearly given up a life-long quest to find The Lost City of "
        story += noun.title()
        story += " when one day, the "
        story += noun
        story += " found "
        story += person + ". "
        story += "A strong, "
        story += adjectives
        story += "peculiar feeling overwhelmed the explorer. "
        story += "After all this time, the quest was finally over. A tear came to "
        story += person + "'s "
        story += body_part + ". "
        story += "And then, the "
        story += noun
        story += " promptly devoured "
        story += person + ". "
        story += "The moral of the story? Be careful what you "
        story += verb
        story += " for."
        
        # display the story                                
        self.story_txt.delete(0.0, END)
        self.story_txt.insert(0.0, story)

# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()

How to use radio buttons using tkinter in Python 3

# Movie Chooser 2
# Demonstrates radio buttons
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI Application for favorite movie type. """
    def __init__(self, master):
        """ Initialize Frame. """
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create widgets for movie type choices. """
        # create description label
        Label(self,
              text = "Choose your favorite type of movie"
              ).grid(row = 0, column = 0, sticky = W)

        # create instruction label
        Label(self,
              text = "Select one:"
              ).grid(row = 1, column = 0, sticky = W)

        # create variable for single, favorite type of movie
        self.favorite = StringVar()

        # create Comedy radio button
        Radiobutton(self,
                    text = "Comedy",
                    variable = self.favorite,
                    value = "comedy.",
                    command = self.update_text
                    ).grid(row = 2, column = 0, sticky = W)

        # create Drama radio button
        Radiobutton(self,
                    text = "Drama",
                    variable = self.favorite,
                    value = "drama.",
                    command = self.update_text
                    ).grid(row = 3, column = 0, sticky = W)

        # create Romance radio button
        Radiobutton(self,
                    text = "Romance",
                    variable = self.favorite,
                    value = "romance.",
                    command = self.update_text
                    ).grid(row = 4, column = 0, sticky = W)

        # create text field to display result
        self.results_txt = Text(self, width = 40, height = 5, wrap = WORD)
        self.results_txt.grid(row = 5, column = 0, columnspan = 3)

    def update_text(self):
        """ Update text area and display user's favorite movie type. """
        message = "Your favorite type of movie is "
        message += self.favorite.get()
            
        self.results_txt.delete(0.0, END)
        self.results_txt.insert(0.0, message)

# main
root = Tk()
root.title("Movie Chooser 2")
app = Application(root)
root.mainloop()

How to use check button using tkinter in Python 3

# Movie Chooser
# Demonstrates check buttons
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI Application for favorite movie types. """
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create widgets for movie type choices. """    
        # create description label
        Label(self,
              text = "Choose your favorite movie types"
              ).grid(row = 0, column = 0, sticky = W)

        # create instruction label
        Label(self,
              text = "Select all that apply:"
              ).grid(row = 1, column = 0, sticky = W)
        
        # create Comedy check button
        self.likes_comedy = BooleanVar()
        Checkbutton(self,
                    text = "Comedy",
                    variable = self.likes_comedy,
                    command = self.update_text
                    ).grid(row = 2, column = 0, sticky = W)

        # create Drama check button
        self.likes_drama = BooleanVar()
        Checkbutton(self,
                    text = "Drama",
                    variable = self.likes_drama,
                    command = self.update_text
                    ).grid(row = 3, column = 0, sticky = W)

        # create Romance check button
        self.likes_romance = BooleanVar()
        Checkbutton(self,
                    text = "Romance",
                    variable = self.likes_romance,
                    command = self.update_text
                    ).grid(row = 4, column = 0, sticky = W)

        # create text field to display results
        self.results_txt = Text(self, width = 40, height = 5, wrap = WORD)
        self.results_txt.grid(row = 5, column = 0, columnspan = 3)

    def update_text(self):
        """ Update text widget and display user's favorite movie types. """
        likes = ""
        
        if self.likes_comedy.get():
            likes += "You like comedic movies.\n"

        if self.likes_drama.get():
            likes += "You like dramatic movies.\n"

        if self.likes_romance.get():
            likes += "You like romantic movies."
      
        self.results_txt.delete(0.0, END)
        self.results_txt.insert(0.0, likes)

# main
root = Tk()
root.title("Movie Chooser")
app = Application(root)
root.mainloop()

How to use text widgets, entry widgets and the grid layout manager with tkinter in Python 3

# Longevity
# Demonstrates text and entry widgets, and the grid layout manager
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI application which can reveal the secret of longevity. """ 
    def __init__(self, master):
        """ Initialize the frame. """
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create button, text, and entry widgets. """
        # create instruction label
        self.inst_lbl = Label(self, text = "Enter password for the secret of longevity")
        self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W)

        # create label for password      
        self.pw_lbl = Label(self, text = "Password: ")
        self.pw_lbl.grid(row = 1, column = 0, sticky = W)

        # create entry widget to accept password      
        self.pw_ent = Entry(self)
        self.pw_ent.grid(row = 1, column = 1, sticky = W)

        # create submit button
        self.submit_bttn = Button(self, text = "Submit", command = self.reveal)
        self.submit_bttn.grid(row = 2, column = 0, sticky = W)

        # create text widget to display message
        self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD)
        self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W)

    def reveal(self):
        """ Display message based on password. """
        contents = self.pw_ent.get()
        if contents == "secret":
            message = "Here's the secret to living to 100: live to 99 " \
                      "and then be VERY careful."            
        else:
            message = "That's not the correct password, so I can't share " \
                      "the secret with you."
        self.secret_txt.delete(0.0, END)
        self.secret_txt.insert(0.0, message)

# main
root = Tk()
root.title("Longevity")
root.geometry("250x150")

app = Application(root)

root.mainloop()

How to use a class with tkinter in Python 3

# Lazy Buttons 2
# Demonstrates using a class with Tkinter
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ A GUI application with three buttons. """ 
    def __init__(self, master):
        """ Initialize the Frame. """
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create three buttons that do nothing. """
        # create first button
        self.bttn1 = Button(self, text = "I do nothing!")
        self.bttn1.grid()

        # create second button
        self.bttn2 = Button(self)
        self.bttn2.grid()	
        self.bttn2.configure(text = "Me too!")

        # create third button
        self.bttn3 = Button(self)
        self.bttn3.grid()
        self.bttn3["text"] = "Same here!"

# main
root = Tk()
root.title("Lazy Buttons 2")
root.geometry("200x85")
app = Application(root)
root.mainloop()

How functions work in Python Programming

Source: https://www.guru99.com/functions-in-python.html

# Declaring arguments
def multiple(x,y)
	print x*y

# Passing arguments
multiply(2,8)

Parameters are temporary variable names within functions. The argument can be thought of as the value that is assigned to that temporary variable. Within the function, parameters act as placeholders for the argument it is passed. [Link]

 

 

How to parse file input in C Programming

/*
* Program to Parse File Input
* From the book: C Programming Visual Quickstart Guide 
*
* Uses the sscanf() function to break the stored data into its indivdual parts.
* Breaking each line into its date, high tempature, and low tempature. Just as
* they were first entered.
*/

#include <stdio.h>

/*
* Set the file path and name.
*/

#define THEFILE "weather.txt"

int main (void) {

/*
* Need a pointer of type FILE.
*/

FILE *fp;

/*
* Character array for reading the file.
*/

char line[30];

/*
* After  defining the line variable, 
* define three more variables.
*/

int high, low;

/*
* In the form of YYYY-MM-DD, plus \0 character.
*/

char date[11];

/*
* Attempt to open the file for reading.
*/

fp = fopen(THEFILE, "r");

/*
* The file is open.
*/

if (fp != NULL) {

/*
* Caption. Using a little printf() formatting
* this application will print out the retrieved
* data in columns
*/

printf("%10s %5s %5s\n", "Date", "High", "Low");

/*
* Loop through the file, parsing each line.
* The condition of the while loop will continue
* to use fgets() to read through the entire file.
* Within the while loop, the process changes. 
* First the sscanf() function is used to break
* the read line into its three distinct parts.
* This structure parallels that used to key
* in the data.
*/

while (fgets(line, sizeof(line), fp)) {

sscanf(line, "%10s %d %d", date, &high, &low);

printf("%10s %5d %5d\n", date, high, low);

}

} else {

printf("The file could not be opened.\n");

/* 
* Exit the function/application.
*/

return 1;
}

/*
* Close the file.
*/

if (fclose(fp) != 0) {

printf("The file count not be closed.\n");

}

/*
* Pause.
*/

getchar();
return 0;

}

How to read from a file in C Programming

/*
* Program to read from files
* From the book: C Programming Visual Quickstart Guide
*/


#include <stdio.h>

/*
* Set the file path and name as a C pre-processor
* macro.
*/

#define THEFILE "read_text.txt"

/*
* Begin main function.
*/

int main (void) {

/* 
* Create a file pointer.
*/

FILE *fp;


/*
* Define the required variable. Only one variable is necessary
* for this application (aside from the pointer.) The line 
* character array will store the data retrived from the text
* file. Its length (30) allows for a resonable amount of data,
* based on what we expect the text file to contain.
*/

char line[30]; 

/*
* Open the file for reading. The r mode is used to only read 
* from a file.
*/

fp = fopen(THEFILE, "r");

/* 
* Start a conditional based on the file pointer and print a
* caption. 
*/

if (fp != NULL) {

printf("The contents of the 'read_text.txt' file:\n");

/*
* Read and print the file's contents in a loop.
* This loop will continue to use the fgets()
* function to read in from the file as long as it 
* can (which is until it reaches the file's end.) 
* With each iteration of the loop, the data read with
* fgets() is assigned to a line variable, which is then
* printed as a simple string.
*/

while (fgets(line, sizeof(line), fp)) {

printf("%s", line);

}

/*
* Complete the fp conditional.
*/

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1; 

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {

printf("The file could not be closed.\n");

}

/* 
* Complete the main function.
*/

getchar();
return 0;

}