Friday, September 23, 2011

C STRUCTURE









REVISED: Sunday, March 15, 2015




CONTENTS:
I.     C STRUCTURE INTRODUCTION
II.    C STRUCTURE VOCABULARY
III.   THE C STRUCTURE
IV.   C STRUCTURE EXAMPLE PROGRAM SOURCE CODE
V.    EXAMPLE PROGRAM OUTPUT
VI.   C STRUCTURE REFERENCES

YOU WILL LEARN: 
1. C structure vocabulary.
2. How to declare a C structure.
3. How memory for a C structure is allocated.
4. How to declare an instance of a C structure.

I. INTRODUCTION

Welcome to the “C Structure Tutorial.”



The C code shown in the tutorial were written using the Microsoft Visual C++ Express Edition Integrated Development Environment (IDE) and the “C99 subset.”

II. VOCABULARY

A. What is a structure?


A structure is a collection of logically related variables of different types. A structure groups logically related standard or user defined data types. Once declared, a structure defines a template for creating compound variable type objects which are instances of a structure.


Structures can be nested as elements in other structures. Structures can be used recursively. Structures can be used to define new data types.

B. What is a tag?


A structure type name is referred to as a tag. The tag appears right after the keyword struct.

If your program uses only one structure_variable, you do not need the structure_type_name.

C. What do you call variables that make up a structure?


Members, elements, or fields are the names of variables that make up the structure.

III. THE C STRUCTURE

A. How do you declare a structure?


The syntax for simultaneously declaring a structure template and creating compound variable type objects is as follows:

struct structure_type_name{
//keyword
struct and tag, user defined type
type member_name;
//members, elements, or fields
type member_name;
type member_name;
.
.
.
}structure_variables;
//compound variable type objects


B. How do you allocate memory for a structure?


Memory is automatically allocated for all the members by the compiler when a structure variable is declared.

C. How do you define an instance of a structure?


After the structure template has been defined, an instance of a physical compound variable type object, a structure_variable can be declared using the following syntax:

struct structure_type_name structure_variable;

IV. EXAMPLE PROGRAM

//**********************************
//  C STRUCTURE TUTORIAL
//**********************************

#include<conio.h>
//contains function prototypes
#include<ctype.h>
//character handling
#include<stdio.h>
//input/output
#include<stdlib.h>
//general utilities
#include<string.h>
//string handling

struct item
//structure declaration
{
    int item_stock_number;
//member, element, or field

    char *item_name;
//member, element, or field

    char *item_description;
//member, element, or field

    float item_cost;
//member, element, or field

    float item_sales_price;
//member, element, or field

    int item_inventory_quantity;
//member, element, or field

}item1, item2, item3;
//compound variable type objects

void f_item1(void);
//function prototype

void f_item2(void);
//function prototype

void f_item3(void);
//function prototype

void p_item1(void);
//function prototype

void p_item2(void);
//function prototype

void p_item3(void);
//function prototype

int main(void)
{
    f_item1();
//function call

    f_item2();
//function call

    f_item3();
//function call

    p_item1();
//function call

    p_item2();
//function call

    p_item3();
//function call

    char ch;
    ch = getch();
//keeps screen from closing
//until a key is pressed
         
    return 0;
}

void f_item1(void)
//function definition
{
    item1.item_stock_number = 128;

    item1.item_name = "Diamond Cufflinks";

    item1.item_description = "Each 3 Carat Skull Shaped, 9K (375Au) yellow gold.";

    item1.item_cost = 250.00;

    item1.item_sales_price = 2500.00;

    item1.item_inventory_quantity = 10;
}

void f_item2(void)
//function definition
{
    item2.item_stock_number = 142;

    item2.item_name = "Ruby Cufflinks";

    item2.item_description = "Each 3 Carat Skull Shapped, 9K (375Au) yellow gold.";

    item2.item_cost = 500.00;

    item2.item_sales_price = 5000.00;

    item2.item_inventory_quantity = 20;
}

void f_item3(void)
//function definition
{
    item3.item_stock_number = 187;

    item3.item_name = "Sapphire Cufflinks";

    item3.item_description = "Each 3 Carat Skull Shapped, 9K (375Au) yellow gold.";

    item3.item_cost = 1000.00;

    item3.item_sales_price = 10000.00;

    item3.item_inventory_quantity = 30;
}

void p_item1(void)
//function definition
{
    printf("Stock Number: %i \n", item1.item_stock_number);

    printf("Name: %s \n", item1.item_name);

    printf("Description: %s \n", item1.item_description);

    printf("Cost: $%.2f \n", item1.item_cost);

    printf("Sales Price: $%.2f \n", item1.item_sales_price);

    printf("Inventory: %i \n\n\n", item1.item_inventory_quantity);
}

void p_item2(void)
//function definition
{
    printf("Stock Number: %i \n", item2.item_stock_number);

    printf("Name: %s \n", item2.item_name);

    printf("Description: %s \n", item2.item_description);

    printf("Cost: $%.2f \n", item2.item_cost);

    printf("Sales Price: $%.2f \n", item2.item_sales_price);

    printf("Inventory: %i \n\n\n", item2.item_inventory_quantity);
}

void p_item3(void)
//function definition
{
    printf("Stock Number: %i \n", item3.item_stock_number);

    printf("Name: %s \n", item3.item_name);

    printf("Description: %s \n", item3.item_description);

    printf("Cost: $%.2f \n", item3.item_cost);

    printf("Sales Price: $%.2f \n", item3.item_sales_price);

    printf("Inventory: %i \n\n\n", item3.item_inventory_quantity);

}

V. EXAMPLE PROGRAM OUTPUT

Stock Number: 128
Name: Diamond Cufflinks
Description: Each 3 Carat Skull Shaped, 9K (375Au) yellow gold.
Cost: $250.00
Sales Price: $2500.00
Inventory: 10

Stock Number: 142
Name: Ruby Cufflinks Description: Each 3 Carat Skull Shapped, 9K (375Au) yellow gold.
Cost: $500.00
Sales Price: $5000.00
Inventory: 20

Stock Number: 187
Name: Sapphire Cufflinks
Description: Each 3 Carat Skull Shapped, 9K (375Au) yellow gold. Cost: $1000.00
Sales Price: $10000.00
Inventory: 30


VI. REFERENCES

The C Programming Language by Brian Kernighan and Dennis Ritchie (Englewood Cliffs, N.J.: Prentice-Hall, 1978).

C++: The Complete Reference, Fourth Edition by Herbert Schildt (Berkeley, California: McGraw-Hill/Osborne, 2003).

YOU HAVE LEARNED: 
1. C structure vocabulary.
2. How to declare a structure.
3. How memory for a structure is allocated.
4. How to declare an instance of a structure.

Elcric Otto Circle






-->





-->





-->







How to Link to My Home Page

It will appear on your website as:
"Link to ELCRIC OTTO CIRCLE's Home Page"






C KEYBOARD INPUT AND SCREEN OUTPUT









REVISED: Sunday, March 15, 2015


CONTENTS:
I.    C KEYBOARD INPUT AND SCREEN OUTPUT INTRODUCTION
II.  READING FROM THE KEYBOARD
III. WRITING TO THE CONSOLE
IV. C KEYBOARD INPUT AND SCREEN OUTPUT REFERENCES

YOU WILL LEARN HOW TO:
1. Read from the keyboard.
2. Write to the console.

I. C KEYBOARD INPUT AND SCREEN OUTPUT INTRODUCTION


Welcome to the “C Keyboard Input and Screen Output Tutorial.”


During this tutorial we will discuss the library functions C uses for keyboard input and screen output. The prototypes for these functions are in the header file conio.h.


C++ includes the entire C language; therefore, all C programs, with a few minor exceptions, are also C++ programs.

The C code shown in the tutorial were written using the Microsoft Visual C++ Express Edition Integrated Development Environment (IDE) and the “C99 subset.”

II. READING FROM THE KEYBOARD


The following are basic keyboard functions:

getchar( ) reads a character from the keyboard; waits for a carriage return. Its prototype is:

int getchar(void);


getche( ) reads a character from the keyboard with echo to the screen; does not wait for carriage return. Its prototype is:

int getche(void);


getch( ) reads a character from the keyboard without echo to the screen; does not wait for carriage return. Its prototype is:

int getch(void);


gets( ) reads a string from the keyboard. Its prototype is:

char *gets(char *str);

str is a character array.


scanf( ) reads data from the keyboard. Its prototype is:

int scanf(const char *control_string, …);


The scanf( ) control string contains three parts. First, format specifiers. Second, white-space characters. Third, non-white-space characters.


Each scanf( ) format specifier is a %, followed by a format code. Each argument is matched with a format specifier in order from left to right.


The following are examples of scanf( ) format specifiers:

%c  Read a single character.
%d  Read a decimal integer.
%i  Read an integer in either decimal, hexadecimal or octal format.
%e  Read a floating point number.
%f  Read a floating point number.
%g  Read a floating point number.
%o  Read an octal number.
%s  Read a string.
%x  Read a hexadecimal number.
%p  Read a pointer.
%n  Receives an integer value equal to the number of characters read so far.
%u  Read an unsigned decimal integer.
%[ ]  Scan for a set of characters.
%%  Read a % sign.


A white-space character in the scanf( ) control string causes scanf( ) to skip over one or more leading white-space characters; e.g., space, tab, vertical tab, form feed, or newline in the input stream.


A non-white-space character in the scanf( ) control string causes scanf( ) to read and discard matching characters in the input stream.

III. WRITING TO THE CONSOLE

The following are basic console functions:


putchar( ) writes a character to the screen. Its prototype is:

int putchar(int c);


puts( ) writes a string to the screen. Its prototype is:

int puts(const char *str);


printf( ) writes data to the console. Its prototype is:

int printf(const char *control_string, …);


The printf( ) control string is in two parts. The first part consists of characters that will be printed to the screen. The second part is format specifiers which define the display of the arguments.


Each printf( ) format specifier is a %, followed by a format code. Each argument is matched with a format specifier in order from left to right.


The following are examples of printf( ) format specifiers:

%c  Character
%d  Signed decimal integers
%i  Signed decimal integers
%e  Scientific notation lowercase e
%E  Scientific notation uppercase e
%f  Decimal floating point
%g  Uses %e or %f, whichever is shorter
%G  Uses %E or %F, whichever is shorter
%o  Unsigned octal
%s  String of characters
%u  Unsigned decimal integers
%x  Unsigned hexadecimal lowercase letters
%X  Unsigned hexadecimal uppercase letters
%p  Displays a pointer
%n  The associated argument must be a pointer to an integer. This specifier causes the number of  characters written so far to be put into that integer.
%%  Prints a % sign

IV. C KEYBOARD INPUT AND SCREEN OUTPUT REFERENCES


The C Programming Language by Brian Kernighan and Dennis Ritchie (Englewood Cliffs, N.J.: Prentice-Hall, 1978).


C++: The Complete Reference, Fourth Edition by Herbert Schildt (Berkeley, California: McGraw-Hill/Osborne, 2003).

YOU HAVE LEARNED HOW TO:
1. Read from the keyboard.
2. Write to the console.

Elcric Otto Circle





--> --> -->







How to Link to My Home Page

It will appear on your website as:
"Link to ELCRIC OTTO CIRCLE's Home Page"






C FILE INPUT AND OUTPUT









REVISED: Sunday, March 15, 2015



CONTENTS:
I.   C FILE INPUT AND OUTPUT INTRODUCTION
II.  C FILE INPUT AND OUTPUT VOCABULARY
III. WRITING TO A FILE
IV. READING FROM A FILE
V.  C FILE INPUT AND OUTPUT EXAMPLE PROGRAM SOURCE CODE
VI. C FILE INPUT AND OUTPUT REFERENCES

YOU WILL LEARN:
1. C input and output vocabulary.
2. How to write to a binary file.
3. How to read from a binary file.

I. C FILE INPUT AND OUTPUT INTRODUCTION


Welcome to the “C File Input and Output Tutorial.”


During this tutorial we will discuss the library functions C uses for file input and output. The prototypes for these functions are in the C header files; for example, <stdio.h>.


C++ includes the entire C language; therefore, all C programs, with a few minor exceptions, are also C++ programs.


The C code examples shown in the tutorial were written using the Microsoft Visual C++ Express Edition Integrated Development Environment (IDE) and the “C99 subset.”

II. C FILE INPUT AND OUTPUT VOCABULARY

A. What is a field?


A field is a group of characters that conveys meaning such as a field representing a color of light.

B. What is a record?

A record is a group of related fields.

C. What is a stream?

A stream is a logical device.


Streams are device independent mental abstractions. When you use scanf() and stdin you are using a keyboard file stream. When you use printf() and stdout you are using a screen file stream.


A stream is a flow of related records. There are two types of streams: text and binary. A sequence of characters is a text file stream. A sequence of bytes is a binary file stream.

D. What is a FILE pointer?


A FILE pointer is used to enable the program to keep track of the stream being accessed, and to let the compiler perform input and output functions.


A program opens a file stream by calling a standard library function. The library function returns a FILE pointer. The file pointer is a pointer to a structure of type FILE. The file pointer points to the unique memory address of a file.


The syntax for a FILE pointer is as follows:

FILE *fp;

E. What is a file?

A file is an actual device.


A file is a container you can both read from and write to.

F. What is a header file?


The header files contain prototypes for the file input and output functions; and macros.


Prototypes declare functions before they are used.

The syntax for a function prototype is as follows:

type function_name(type parameter_name1, type parameter_name2,…, type parameter_nameN,);


When a function has no parameters, use void inside the parameter list.

type function_name(void);

G. What is POD?


POD is Plain Old Data. For example, in the case of a POD structure, the structure would contain no pointers and all members would be of a fixed size.

H. What is a Library?


C provides the basic functions you need to get started. However, you have to code everything else yourself.


When you notice you are rewriting the same code over and over take the time to turn that code into a generic library function.


A library consists of two parts: a header file and the actual code file. The library header file uses quotes instead of the symbols < and >, which are only used for system libraries.


Library C function calls should always pass arguments by value. In other words use regular function variables, do not use function pointers. This is done to ensure that only local “copies” of the values of the arguments are passed to the library function. Therefore, all changes made to the arguments in the local copy of the library function are only made to the local copy of the arguments and not to the original arguments themselves.

III. WRITING TO A FILE

Writing to a file requires three steps:

A. Open the file.


To open a file use the fopen function, which returns a FILE pointer.

The open operation return pointer associates a stream with a specific file. If the file can not be opened, the return pointer is set to the value NULL.

The syntax for opening a file is as follows:

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


The filename is a string containing the name of the file to be opened.


The mode is a string containing the way the file will be used.

Text file modes are as follows:


r Open file for reading. File must exist. NULL pointer returned if file does not exist.


w Open for writing. If file does not exist it is created. If file does exist it will be overwritten.


a Open file for appending. If file does not exist it is created. Appends if file exists.


r+ Open file for reading and writing. File must exist. Starts at beginning of existing file.


w+ Open file for reading and writing. If file does not exist it is created. Overwrites existing file.


a+ Open file for reading and writing. If file does not exist it is created. Appends if file exists.

Binary file modes are as follows:


rb Open file for reading. File must exist. NULL pointer returned if file does not exist.


wb Open for writing. If file does not exist it is created. If file does exist it will be overwritten.


ab Open file for appending. If file does not exist it is created. Appends if file exists.


r+b Open file for reading and writing. File must exist. Starts at beginning of existing file.


w+b Open file for reading and writing. If file does not exist it is created. Overwrites existing file.


a+b Open file for reading and writing. If file does not exist it is created. Appends if file exists.


For binary File I/O you use fread and frwrite.


When typing a file path, type double back-slashes. For example, typing 

"j:\folder\example1.bin"

 will not work.

 You have to type

 "j:\\folder\\example1.bin". 


The folder has to exist. The program will crash if the folder does not exist.


An example of opening a binary file for writing is as follows:

FILE *fp;
fp=fopen(“j:\\examples\\example1.bin”,”wb”);


This code will open the binary file named example1.bin on drive j: in folder examples for writing. If file does exist it will be overwritten. If the file does not exist it will be created.


Always test to make sure the file opened before you try to write to the file.


An example of testing whether a file did not open is as follows:

if ((fp = fopen ("j:\\examples\\example1.bin","wb")) == NULL)
{
printf ("ERROR MESSAGE!  File could not be opened!\n");
}


Once you know the file opened properly, use the FILE return pointer to tell the compiler to perform input and output functions on the file.


Use fread() and fwrite() for binary file fixed-length record I/O; for example:

size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);

fwrite() takes four arguments:

1. const void * buffer


The first argument is a pointer to the name of the array or the address of the structure you want to write to the file.

2. size_t num_bytes


The second argument is the size of each element in bytes.


For example, if you have an array of characters, you would read the array in one byte at a time. Therefore, num_bytes would be one.

3. size_t count


The third argument is the count of the number of elements you want to write.

4. FILE * fp


The fourth argument is the stream file pointer.

B. Do all the writing.


An example of writing to a binary file is as follows:

//write to binary file
           
            FILE *fp;
            fp=fopen("j:\\examples\\example1.bin", "wb");

            if (fp == NULL)
            {
            printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");

            }else
            {
                printf("  Binary file opened!\n\n\n\n");

                fwrite(&write, sizeof(write[0]), sizeof(write)/sizeof(write[0]), fp);

                printf("  %s character string array was written to the binary file.\n\n\n\n", write);

            }

            int returncode;

            returncode = fclose (fp);
           
            if (returncode == 0)
            {
                printf ("  Binary file closed!\n\n\n\n");

            }else
            {
                printf ("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");

            }


C. Close the file.


Always close a file as soon as you are done using it. The syntax for closing a file is as follows:

int returncode;

returncode = fclose (fp);



if returncode == 0; the file pointed to by fp closed.


if returncode != 0; the file pointed to by fp did not close.


Always test to make sure the file closed. Zero is returned if the file closed. EOF is returned if the file did not close.

An example of testing whether a file closed is as follows:

if (fclose(fp) != 0)
{
printf ("ERROR MESSAGE!  File did not close!\n");
}


if fclose(fp) == 0; the file pointed to by fp closed.


if (fclose(fp) != 0); the file pointed to by fp did not close.

IV. READING FROM A FILE

Reading from a file requires three steps:

A. Open the file.


Test to make sure the file opened before you read the file.

//read from binary file

            FILE *fpRead;
            fpRead=fopen("j:\\examples\\example1.bin", "rb");

            if (fpRead == NULL)
            {
                printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");

            }else
            {
                printf ("  Binary file opened!\n\n\n\n");

B. Do all the reading.


The input file that we are opening for reading must already exist.

fread(&read, sizeof(read[0]), sizeof(read)/sizeof(read[0]), fpRead);

C. Close the file.

The syntax for closing a file is as follows:

printf("  %s character string array was read from the binary file.\n\n\n\n", read);

            }
           
            int returncodeRead;

            returncodeRead = fclose (fpRead);
           
            if (returncodeRead == 0)
            {
                printf("  Binary file closed!\n\n\n\n");

            }else
            {
                printf("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");

            }


V. C FILE INPUT AND OUTPUT EXAMPLE PROGRAM SOURCE CODE

//***********************************
//C FILE INPUT AND OUTPUT TUTORIAL
//***********************************

#include<conio.h>
//contains function prototypes
#include<stdio.h>
//standard I/O header file
#include<string.h>
//string handling
#include<windows.h>
//  keybd_event()

void ShowTime(void);

void AltEnter(void);

void DateTime(void);

void menu(void);

//**********************************

int main(int argc, char *argv[])
{
    ShowTime();

    menu();  
         
    return EXIT_SUCCESS;
}

//**********************************

void ShowTime(void)
{
    AltEnter();

    system("COLOR 1F");

    return;
}

void AltEnter(void)
{
    keybd_event(VK_MENU,
                0x38,
                0,
                0);
    keybd_event(VK_RETURN,
                0x1c,
                0,
                0);

    keybd_event(VK_RETURN,
                0x1c,
                KEYEVENTF_KEYUP,
                0);

    keybd_event(VK_MENU,
                0x38,
                KEYEVENTF_KEYUP,
                0);

    return;
}

void DateTime(void)
{
    printf("\n");

    printf("\n");

    printf("\n");

    printf("                              ");

    printf(__DATE__);

    printf("    ");

    printf(__TIME__);

    printf("\n");

    printf("\n");

    return;
}

void menu(void)
{
    system("CLS");

    DateTime();

    printf("\n\n                      C FILE INPUT AND OUTPUT TUTORIAL \n\n\n\n");
   
    printf("  0  EXIT\n\n");

    printf("  1  Write a character string array to a binary file\n\n");

    printf("     and then read that character string array from the same binary file.\n\n\n");

    printf("\n\n  Please type your menu selection; for example, 0 to EXIT.\n\n  ");

    char menuSelection;

    menuSelection = getch();

    switch(menuSelection)
    {
        case '0':
            break;

        case '1':
            system("CLS");

            DateTime();

            printf("\n\n                      C FILE INPUT AND OUTPUT TUTORIAL \n\n\n\n");

            char write[10]="ELEPHANTS";

            char read[10];

            for (int i=0; i++; i<=10)
            {
                read[i]='\n';

            }
           
//write to binary file
           
            FILE *fp;
            fp=fopen("j:\\examples\\example1.bin", "wb");

            if (fp == NULL)
            {
            printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");

            }else
            {
                printf("  Binary file opened!\n\n\n\n");

                fwrite(&write, sizeof(write[0]), sizeof(write)/sizeof(write[0]), fp);

                printf("  %s character string array was written to the binary file.\n\n\n\n", write);

            }

            int returncode;

            returncode = fclose (fp);
           
            if (returncode == 0)
            {
                printf ("  Binary file closed!\n\n\n\n");

            }else
            {
                printf ("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");

            }

//read from binary file

            FILE *fpRead;
            fpRead=fopen("j:\\examples\\example1.bin", "rb");

            if (fpRead == NULL)
            {
                printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");

            }else
            {
                printf ("  Binary file opened!\n\n\n\n");

                fread(&read, sizeof(read[0]), sizeof(read)/sizeof(read[0]), fpRead);

                printf("  %s character string array was read from the binary file.\n\n\n\n", read);

            }
           
            int returncodeRead;

            returncodeRead = fclose (fpRead);
           
            if (returncodeRead == 0)
            {
                printf("  Binary file closed!\n\n\n\n");

            }else
            {
                printf("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");
            }
                                       
            printf("\n\n  Type any key to continue.\n\n  ");

            char screenOpen;

            screenOpen = getch();
//keeps screen open until a key is pressed

            menu();
  
            break;                                                                                          
   }
}


VI. C FILE INPUT AND OUTPUT REFERENCES


The C Programming Language by Brian Kernighan and Dennis Ritchie (Englewood Cliffs, N.J.: Prentice-Hall, 1978).


C++: The Complete Reference, Fourth Edition by Herbert Schildt (Berkeley, California: McGraw-Hill/Osborne, 2003).

YOU HAVE LEARNED:
1. C input and output vocabulary.
2. How to write to a binary file.
3. How to read from a binary file.

Elcric Otto Circle




--> --> -->







How to Link to My Home Page

It will appear on your website as:
"Link to ELCRIC OTTO CIRCLE's Home Page"