How to use a linked list in C Programming

/* 
* Program to use linked lists
* From the book: C Programming Quickstart Visual Guide
*
* By adding pointers to the definations of a structure,
* we can create a linked list of unlimited length. (well,
* limited only by the amount of available memory).
*/

#include <stdio.h>
#include <string.h> // For string functions.
#include <stdlib.h> // For memory functions.

#define STR_LEN 20

int main (void) {

/*
* Define the structure.
*/

struct student_grade {
char first_name[STR_LEN];
char last_name[STR_LEN];
float grade;
struct student_grade *next;
};

/*
* Rename the structure syntax.
*/

typedef struct student_grade sg;

/*
* Create two structure pointers.
*/

sg *first = NULL;
sg *new = NULL;
sg *temp = NULL;

int num; // For counting the input.

/*
* Need a temporary float.
*/

float g; //grade

/*
* Need some strings to handle the input.
*/

char classname[12], fn[STR_LEN], ln[STR_LEN];

/*
* Prompt the user.
*/

printf("Enter the classname (without spaces): ");
scanf("%11s", classname);

/*
* Prompt the user again.
*/

printf("Enter the student's name and their grade. Enter 0 0 0 to quite.\n(First Last ##.#): ");

/*
* Read the input.
*/

num = scanf("%11s %11s %f", fn, ln, &g);

/*
* Check if the user is done
*/

while (fn[0] != '0') {

/*
* Handle input.
*/

if (num == 3) {

new = (sg *) malloc(sizeof(sg));

/*
* Check that new is not NULL.
*/

strncpy(new->first_name, fn, STR_LEN-1);

new ->first_name[STR_LEN-1] = '\0';

strncpy(new->last_name, ln, STR_LEN-1);

new->last_name[STR_LEN-1] = '0';

new->grade = g;
new->next = first;
first = new;

} else {

printf("The data was not in the proper format.\n");
}

/*
* Prompt the user.
*/

printf("Enter the studen's name and their grade. Enter 0 0 0 to quit.\n(First Last ##.#): ");

/*
* Read the input.
*/

num = scanf("%11s %11s %f", fn, ln, &g);

} // End of while loop

/*
* Print the data and free the memory.
*/

printf("Student and grades for the class '%s':\n", classname);

new = first; //Start at the beginning.

while (new != NULL) { //Stop when list is done.

printf("%s %s %01.f\n", new->first_name, new->last_name, new->grade);

temp = new->next;
free(new);
new = temp;

}

getchar(); //Pause
getchar();//Pause
return 0;

}

How to use an array of structures in C Programming

/*
* Program to use arrays of structures
* From the book: C Programming Visual Quickstart Guide
*
* Structures, just like integers, floats,
* and characters, can be used in arrays.
* This program creates a list of student
* names and gradesby taking input from 
* the user and storing it in an array
* of structures.
*/

#include <stdio.h>
/* 
* In order to use the strncpy() function,
* the string.h file must be included.
*/
#include <string.h>

/*
* Define two macro constants. The first 
* represents the maximum string length
* (for a person's first and last names.)
* The second will be the number of 
* elements in the array.
*/

#define STR_LEN 20

#define NUM_STUDENTS 10

int main (void) {

/*
* Define the structure. The structure
* has two character arrays and one float.
*/

struct student_grade {
char first_name[STR_LEN];
char last_name[STR_LEN];
float grade;
};

/*
* Use typedef to rename the structure 
* syntax, then create an array of 
* structures. The typedef simplififes
* the process of referring to a structure.
* Then an array of structures called class
* is created.
*/

typedef struct student_grade sg;

/*
* Create an array of structures.
*/

sg class[NUM_STUDENTS];

/* 
* Need some counters.
*/

int i, num;
int count =0;

/*
* Need some strings to handle the input.
*/

char classname[12], fn[STR_LEN], ln[STR_LEN];

/*
* Need a temporary float.
*/

/*
* grade
*/

float g;

/* 
* Prompt the user.
*/

printf("Enter the classname (without spaces): ");
scanf("%11s", classname);

/* 
* Loop to read in all the student data.
*/

for(i = 0; i < NUM_STUDENTS; ++i) {

/*
* Prompt the user.
*/

printf("Enter the student's name and their grade. Enter 0 0 0 to quit.\n(First Last ##.#): ");

/*
* Read in the input.
*/

num = scanf("%11s %11s %f", fn,ln, &g);

/*
* Check if the user is done.
*/

if(fn[0] == '0') {
break;
}

/*
* Handle the input.
*/

if(num == 3) {

strncpy(class[i].first_name, fn, STR_LEN-1);

class[i].first_name[STR_LEN-1] = '\0';

strncpy(class[i].last_name, ln, STR_LEN-1);

class[i].last_name[STR_LEN-1] = '\0';

class[i].grade = g;
++count;

/*
* Improper input format.
*/
} else {

printf("The data was not in the proper format.\n");
break;
}
}

/*
* Print the data.
*/

printf("Students and grades for the class '%s':\n", classname);

for(i = 0; i < count; ++i) {

printf("%s %s %0.1f\n", class[i].first_name, class[i].last_name, class[i].grade);
}

/*
* Pause.
*/

getchar();
getchar();
return 0;

}

How to use typedef in C Programming

/* 
* Program to use typedef
* From the book: C Programming Visual Quickstart Guide
*
* The typedef operator can help shorten how you
* refer to structures. This application uses 
* those structures to read data from a binary 
* file.
*/

#include <stdio.h>

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

#define THEFILE "weather.dat"

int main(void) {

/* 
* Define the structure.
*/

struct weather_record {
char date[11];
int high;
int low;
};

/* 
* Use typedef to create an alias.
* The first line  makes an alias so that 
wr (short for weather_record) stands for 
struct weather_record. Then wr is used to
* create a day variable of type struct
weather_record.
*/

typedef struct weather_record wr;

/*
* Create a structure variable.
*/

wr day;

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

FILE *fp;

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

fp = fopen(THEFILE, "rb");

/*
* The file is open.
*/

if (fp != NULL) {

/*
* Loop through the entire file, assigning each structure to day.
*/

while(fread(&day, sizeof(wr), 1, fp)) {

/* 
* Print the information using the structure's field.
*/

printf("Date: %s\nHigh: %d\nLow: %d\n\n", day.date, day.high, day.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 cound not be closed.\n");
}

/*
* Pause
*/

getchar();
return 0;

}

How do I use structures in C Programming

/*
* Program to use structures
* From the book: C Programming Visual Quickstart Guide
*
* One structure at a time is written to a binary file
*/

#include <stdio.h>

/*
* Set the file path and name as a C preprocessor macro.
*/

#define THEFILE "weather.dat"

int main (void) {

/*
* Define a structure and create a variable of that type.
* The structure will be called weather_record. It contains
* three members: a character array called date, an integer
* called high, and another integer called low. Each of 
* these correspond to the variables that were used in the
* previous versions of this application. 
* One variable of the weather_record type is created, 
* called today. Note that you have to use both the 
* keyword struct as well as the structure name in
* defining this variable.
*/

struct weather_record {
/*
* YYYY-MM-DD
*/
char date[11];

int high;
int low;

};

/* 
* One structure variable of type weather_record.
*/

struct weather_record today;

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

FILE *fp;

/* 
* Attempt to open the file for appended binary writing.
*/

fp = fopen(THEFILE, "ab");

/*
* The file is open.
*/
if (fp != NULL) {

/*
* Prompt the user.
*/

printf("Enter a date, the high tempature, and the low tempature.\n(YYYY-MM-DD ## ##): ");

/* 
* Handle the input, assigning it to the structure fields.
*/

if(scanf ("%10s %d %d", today.date, &today.high, &today.low) ==3) {

/*
* Write the data.
*/

fwrite(&today, sizeof(struct weather_record), 1, fp);
printf("The data has been written.\n");

} else {

printf("The data was not in proper format.\n");
}

} 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");
}

/*
* Pause
*/
getchar();
getchar();
return 0;

} 

How to navigate a binary file in C Programming

/*
* Program to navigate a binary file
* From the book: C Programming Visual Quickstart Guide
*
* A random point in the data file is used to
* return a "lucky number."
*/

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

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

#define THEFILE "numbers.dat"

/* 
* Numbers of items being written.
* Creat a constant macro representing
* the number of items in the array.
*/

#define ITEMS 50

int main(void) {

/* 
* Need a pointer of type FILE
*/

FILE *fp;

/*
* Two integers are required.
* The first integer will be used as the
* off-set: the location within the number
* file to move to. The second will store 
* the read-in number value.
*/

int offset, number;

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

fp = fopen(THEFILE, "rb");

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

if (fp != NULL) {

/*
* Find a random offset in bytes.
* The first line seeds the rand() funcion.
* The second line picks an arbitrary offset,
* as a random number up to the number of items
* stored. After this second line of code, offset
* will be qual to a number between 0 and 49, 
* corresponding to the 50 items originally stored
* in the file (like an array though, we begin
* counting at 0.)
* The third line multiplies the value of offset
* by the size of an integer. This is neccessary
* because we need to specify the offset in bytes.
* For example, if the randomly generated value is 
10, then the offset needs to be 40 bytes: 10 times
* sizeof(int), normally 4 bytes.
*/

srand((unsigned)time(NULL));
offset = rand() % ITEMS;
offset *= sizeof(int);

/* 
* Move to the random location and read in a number.
* The first line moves the virtual marker offset
* bytes into the file, starting from the beginning
* of the file. The second line reads one bk of data
* of sizeof(number) bytes and stores this in the 
* number variable. Remember that the fread() 
* function takes an address of a variable as its 
* first argument, so &number is used (the memory
* addres of the number variable.)
*/

fseek(fp, offset, SEEK_SET);
fread(&number, sizeof(number), 1, fp);

/*
* Print the number.
*/

printf("Your lucky number is: %d.\n", number);

} 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");

}

/* 
* Pause.
*/

getchar();

return 0;

}

How to read from a binary file in C programming

/*
* Program to read from a binary file
* From the book: C Programming Visual Quickstart Guide
*/

#include <stdio.h>

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

#define THEFILE "numbers.dat"

/*
* Number of the items being wrritten.
*/

#define ITEMS 50

int main (void) {

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

FILE *fp;

/*
* Loop counter
*/

int i;

/*
* Array of numbers.
*/

int numbers[ITEMS];

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

fp = fopen(THEFILE, "rb");

/*
* The file is open.
*/

if (fp != NULL) {

printf("The contents of the numbers file:\n");

/*
* Read the entire contents into the numbers array.
*/

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

/*
* Print each element.
*/

for (i = 0; i < ITEMS; i++) {

printf("%d\n", numbers[i]);

}

} 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");
}

/*
* Pause
*/

getchar();
return 0;

}

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;
}

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;

}

How to write to a file in C Programming

/* 
* Program that writes to a text file
* From the book: Visual Quickstart Guide C Programming
*
* The record_weather application takes three user input values
* (a date, the day's high tempature, and the day's low tempature)
* and writes them to a text file.
*/



#include <stdio.h>

/*
* Set the file path and name as a C preprocessor macro.
*/

#define THEFILE "weather.txt"

/* 
* Begin main function.
*/

int main(void) {

/*
* Create a file pointer.
*/

FILE *fp;

/*
* Define the required variables. The first two variables are
* integers that will store the entered high and low tempatures.
* The data variable is a character array to store dates in the 
* format. YYYY-MM-DD.
*/

int high, low;

char date[11];

/*
* Open the file for appended writing. By using an a, each new
* record will be appended to the end of the file, rather than 
* wipping out any existing data.
*/

fp = fopen(THEFILE, "a");

/*
* Start a condional bases on the file pointer and prompt the user. 
* If the file can be opened, then the user will be promplted for
* the required information.
*/

if (fp != NULL) {

printf("Enter a date, the high tempature, and the low tempature.\n(YYYY-MM-DD ## ###): ");

/*
* Handle the keyed input. Using the scanf() function, the 
* application attempts to read one string (of up to 10
* chracters long) and two integers from the standard input. 
* The string will be stored in date, which as a character
* array, can be listed directly. The two integer values go
* into high and low, which as numbers must be referenced in
* their address form (&). If scanf() successfully read in
* three items, the user entered the information properly,
* so the conditional checks if the returned value is equal 
* to 3. 
*/

if (scanf ("%10s %d %d", date, &high, &low) == 3) {

/*
* Write the data  the text file. The fprintf() function
* will write the values to the text file. The formatting
* is simple: seperate eac value by a space and ending with
* a newline.
*/

fprintf(fp, "%s %d %d\n", date, high, low);

/*
* Complete the scanf() conditional. The first message
* completes the condtional if scanf() worked, 
* indicating that the data was written to the file. 
* If scanf() did not return a value of 3, the input was
* not of the proper format and the second message is
* printed on the screen.
*/

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

/*
* Complete the fp conditional. If the application could
* not open the file for writing, there's no reason to
* continue. Because functions always stop running after
* a return staion this effectively stops the application. 
*

} else {

printf("The data was not in the promper format.\n");

}

} else {

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

return 1;

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {

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

} 

/*
* Complete main function
*/

getchar();
getchar();
return 0;

}