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;

}

How to open and close a file in C Programming

/*
* Program to open and close a file
* From the book: Visual Quickstart Guide
*
* This application opens and then closes a text file to
* ensure that the process works.
*/

#include <stdio.h>

/*
* Set the file path and name as a C preprocessor macro.
* By setting this value as a C preprocessor directive, 
* you won't need to go hunting through your code to find
* the filename if you want to change it later. You have to 
* use the double quotation marks as part of the defination,
* since the fopen() function, which uses this macro later, 
* expects a string.
*/

# define THEFILE "text.txt"

/*
* Begin the main function.
*/

int main (void) {

/*
* Create a file pointer. This is the file pointer that will be
* used to reference the file. 
*/

FILE *fp;

/*
* Open the file for writing. The lines uses in the C preprocessing
* macro defined earlier. Before the compilation of the C cde, the
compiler will replace THEFILE here with the value established earlier.
* The w mode is used, indicating that we want to write to the file, 
* that is should be created if it doesn't exist, and that any existing
* content should be overwritten.
*/

fp = fopen(THEFILE, "w");

/*
* Creating a conditional to report on the file opening. This conditional
* compares the value of the file pointer against NULL. As long as fp does
* not equal NULL, the file was successfully opened for writing. 
*/

if (fp != NULL) {
    printf("The file is now open.\n");
    } else {
        printf("The file could not be opened.\n");
    }


/* 
* Close the file. The fclose() function returns the number 0 if it worked
* properly, so this conditional reports on its success. 
*/ 

if (fclose(fp) != 0) {
    printf("The file could not be closed.\n");
    } else {
    printf("The file is now closed.\n");
    }
    
/*
* Complete the main function.
*/

getchar();
return 0;

}

How to sort a list of strings using pointers

/*
* Program to sort a list of strings using pointers 
* Original Code:
* http://www.algolist.net/Cpp/Pointers_in_depth
*
* To sort strings let's use build-in qsort function. 
* We can't sort strings themselves, but we can sort pointers to them. 
* To compare two pointers we design special function, which compares them,
* taking into account that they point to strings. So, actually, this 
* function compares two strings. Qsort will give us two void pointers 
* pointing to a pair of elements of the source array. Since we are sorting 
* array of pointers to chars, comparison function get two pointers to pointers to chars.
*/

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

 

int readLine(char **pStr) {

      char buf[256];

      int len;

      printf("Input string: ");

      fgets(buf, sizeof(buf), stdin);

      len = strlen(buf);

      // remove new line character

      if (buf[len - 1] == '\n')

            buf[len - 1] = 0;

      *pStr = (char *)calloc(len, sizeof(char));

      strcpy(*pStr, buf);

      return len;

}

 

int readLines(char ***pStrings) {

      int n, i;

      printf("How many strings to input: ");

      scanf("%d", &n);

      // skip newline

      getc(stdin);

      *pStrings = (char **)calloc(n, sizeof(char *));

      for (i = 0; i < n; i++)

            readLine(&(*pStrings)[i]);  

      return n;

}

 

int compareStrings(const void *pStr1, const void *pStr2) {

      return strcmp(*(char **)pStr1, *(char **)pStr2);

}

 

int main() {           

      char **strings;

      int n, i;

      n = readLines(&strings);

      qsort(strings, n, sizeof(char *), compareStrings);

      printf("Sorted strings: \n");

      for (i = 0; i < n; i++)

            printf("%s\n", strings[i]);

      // free memory

      for (i = 0; i < n; i++)

            free(strings[i]);

      free(strings);

      system("PAUSE");

      return 0;

}

How to copy a string in C Programming

/*
* Program to copy a string
* From the book: Visual Quickstart Guide C Programming
*
* This application reads in up to 10 (NUM_STRINGS) words
* of 10 (STR_LEN) characters in length, copying them each 
* into an array.
*/

#include <stdio.h>

/*
* The strings.h headers is required since it defines 
* strncmp() and strcmp().
*/

#include <strings.h>
#include <string.h>

/*
* Function prototype.
*/

void discard_input (void); 

/*
* Set two constant macros. The words entered by the user will
* be stored in a multidimensional character array whos parameters
* are set by these constants. The application will take up to 
* NUM_STRINGS words, each of which can be up to STR_LEN characters
* long.
*/

#define NUM_STRINGS 10
#define STR_LEN 10

/* 
* Begin main function
*/

int main (void) {

/*
* Define two character arrays. The first array will store all the 
* submitted words. The second character array will be used to retrieve
* the keyed input.
*/

char words[NUM_STRINGS][STR_LEN];
char input[STR_LEN];

/* 
* Define two integers. The i variable is a loop counter. To track the 
* total number of words the user entered --- which can be up to 10, the
* count variable will be incremented.
*/

int i;
int count = 0;

/*
* Define a for loop. To read all 10 words, a loop will be used. This 
* iterates from 0 to 1 less than NUM_STRINGS.
*/

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

/*
* Prompt for and read in a word. A word will be read in of up to 9 
* characters in length (allowing for the tenth avaible spot to be 
* filled with \0). The read-in value is assigned to the input 
* character array and then any extraneous input is discarded.
*/

printf("Enter a word (or 0 to quit): ");
scanf("%9s", input);
discard_input();

/*
* Check that the user didn't type a 0. If the user wants to exit the
* application and enter no more words, they can indicate this by
* entering 0. This conditional then checks if the first character in
* the input array is equal to 0. If so, the break will exit the for 
* loop (it has no effect on the if conditional). Since the break is
* the only if statement, curly braces can be ommited for brevity. 
*/

if (input[0] == '0') break;

/* 
* Copy the inputted word into the array. With each iteration of the
* loop, the input variable will be replaced with a new word. Therefore,
* the original value will be copied over to the words array. By using i,
* the loop counter, as its index we ensure that each entered word will
*populate the next avaiable spot in the array. Even though we know the
* input is at most 9 characters long, the third argument in 
* strncpy() is set to STR_LEN so that buffer overflow cannot occur.
*/

strncpy(words[i], input, STR_LEN);

/*
* Complete the while loop. The count variable will be used to count the
* number of submiited words, so its value is incremented by 1.
*/

    ++count;
}

/*
* Print the number of submitted words.
*/

printf("A total of %d words was entered.\n", count);

/*
* Complete the main function
*/

getchar();
return 0;
}

/*
* Define the discard_input() function
*/

void discard_input (void) {
    char junk;
    do {
            junk = getchar();
    } while (junk!= '\n');
}

                

    

How to compare two strings in C Programming

/*
* Program to compare two strings
* From the book: Visual Quickstart Guide C Programming
*
* This guessing game reads in a word and compares it to the right answer.
* The process continues until the users guesses the correct word.
*/

#include <stdio.h>
/*
* strings.h needs to be included to use the strcasecmp() function
*/
#include <strings.h>

/*
* Function prototype. Because this application relies so heavily on precise
* user input, it will utilize the discard_input function. This prototype
* indicates that the function takes no arguments and returns no values.
*/

void discard_input (void);

/* 
* Begin the main function.
*/

int main (void) {

/*
* Define two character arrays. The first array will store the user's guess. 
* The second array is a constant that stores the right answer, which is
* initialized here as well.
*/

char guess[10];
const char answer[] = "coy";

/*
* Prompt for and read in the user's first guess.
*/

printf("Guess what three-letter word I'm thinking of: ");
scanf("9%s", guess);

/*
* Discard any extaneous input. Calling this function here will discard any 
* other characters typed after the application has read in the nine (or up
* to nine) characters assigned to guess. By using this, we ensure that any
* extraneious characters will be discarded instead of beign read in as part
* of the next guess.
*/

discard_input();

/* 
* Begin a while loop to compare to the user's answer against the right word.
* The while loop evaluates a condition and, if true, executes the code therein.
* With this specific loop, the condition is a call to the strcasecmp() function,
* comparing the value of answer to the value of guess. If the two strings do not
* have the same value, the function will return a nonzero value, which is true
* in C. In such cases, the contents of the loop which says the guess was wrong
* and that this user should try again, are executed. If the submitted guess
* matches the right answer, the strcasecmp() function will return 0, which is
* false in C, and the loop will not be entered.
*/

while (strcasecmp(answer, guess)) {

/*
* Complete the while loop, re-prompting the user, reading in the answer, and
* discarding any extraneous input. The contenets of the while loop will only
* be executed if the strcasecamp() function determines that guess and answer
* are different. If so, the user is re-prompted, the next guess is read in,
* and the remaining input is discarded. After these three lines of code have 
* been executed, the loop's condition will be reevaluated -- testing the new
* guess against the right answer. The process will continue until the user
* guesses the correct answer.
*/

printf("Incorrect! Guess again! ");
scanf("%9s", guess);
discard_input();
}

/*
* Tell the user they got it right. The application will only reach this point
* in the code - after the while loop -- if the user enters the correct answer.
*/

printf("You are correct!"); 

/*
* Complete the main function
*/

getchar();
return 0;

}

/*
* Define the discard_input function()
*/

void discard_input (void) {
    char junk;
    do {
            junk = getchar();
    } while (junk!= '\n');
    }
    
                

How to perform concatenation in C Programming

/*
* Program to perform concatenation
* From the book: Visual Quickstart Guide C Programming
*
*Using concatenation, one stringe (name) is
* appended with other string values.
*/

#include <stdio.h>

/*
* Include the string.h header to use both the
* strcat() and strncat() functions
*/

#include <string.h>

/*
* Define the maxiumum variable size. By setting
* this value---which will be used to define the
* character arrays---as a constant, we can use 
* it repeatedly in the application to help avoid
* buffer overflow problems.
*/

#define VARSIZE 50

/*
* Begin the main function
*/

int main (void) {

/* 
* Define two character arrays. the name variable
* will, in the end, contain the user's entire name. 
* The last_name value will be read in seperately and
* appended to name. Both are VARSIZE length.
*/

char name[VARSIZE];
char last_name[VARSIZE];

/* 
* Prompt for and read in user's first name. The scanf()
* function will assign input from the keyboard to the 
* name variable. It will read up to 48 characters or
* until it encounters a space. The 48 limit is imposed
* as 48 characters, plus a space and the terminating \0
* characters, adds up to the 50-character limit for the
 *string.
*/

printf("Enter your first name: ");
scanf("%48s", name);

/*
* Prompt for and read in the user's last name. The same
* process as above is repeated, this time initializing
* the last_name variable.
*/

printf("Enter your last name: ");
scanf("%48s", last_name);

/*
* Using concatenation, add a space to the name variable.
* Before appending the last name to the name variable,
* the script adds a space. In this case you can use the
* strcat() function instead of strncat(), since you know
* that exactly one character will be added to name and
* that the variable has room for it (because a maximum of
* 48 characters have been assigned already.)
*/

strcat(name, " ");

/*
* Append the last name value to the name variable. Here
* the strncat() function is used to append a certain
* number of characters from last_name to name. The number
* of characters available is calculated by starting with 
* the variable's maximum length and subtracting 1 (for the
* space), then subtracting the current number of characters
* already in name. This last number is returned by the
* strlen() function.
*/

strncat(name, last_name, (VARSIZE - 1) - strlen(name));

/* 
* Print the final name variable.
*/

printf("You entered your name as %s.\n", name);

/*
* Complete main function.
*/

getchar();
getchar();
return 0;

}

How to determine the length of a string in C Programming

/*
* Program to determine the length of a string.
* From the book: Visual Quickstart Guide C Programming
*
* The space requirements of the two variables are 
* calculated using the sizeof() and strlen()
* functions. 
*/

#include <stdio.h>

/*
* To use teh strlen() function you must included
* the string.h header file where that macro is 
* defined.
*/

#include <string.h>

/*
* Set the different chapter titles as constant 
* macros.
*/

#define CHAPTER0 "Introduction"
#define CHAPTER1 "Getting Started with C"
#define CHAPTER2 "Introduction to Data Types"
#define CHAPTER3 "Working with Numbers"
#define CHAPTER4 "Control Structures"

/*
* Begin main function
*/

int main (void) {

/*
* Create a multi-dimensional character array.
*/

char chapters[5][27] = {CHAPTER0, CHAPTER1, CHAPTER2, CHAPTER3, CHAPTER4};

/* 
* Create an array of character pointers.
*/

char *chapters_ptr[5] = {CHAPTER0, CHAPTER1, CHAPTER2, CHAPTER3, CHAPTER4};

/*
* Declare three integers. The first variable i, will be a for loop counter.
* The next two variables will be used to total up the number of characters 
* and bytes required by the two arrays. 
*/

/*
* Loop counter
*/

int i;

/*
* Character counters.
*/

int chapters_count = 0, ptr_count = 0;

/*
* Print the memory requirements of each variable.
*/

printf("The chapter arary uses %zu bytes of memory. \n", sizeof(chapters));

printf("The chapters_ptr array uses %zu bytes of memory.\n", sizeof(chapters_ptr));

/* 
* Determine the total string length.
* After the original print statement, use a loop to calculate
* the total length of the strings. The loop will go through
* each subarray of chapters, adding that string's character
* count to the total.
*/

for (i=0; i < 5; ++i) {
    chapters_count += strlen(chapters[i]);
    }
    
/* 
* Print the number of characters.
*/    

printf("Thechapters array contains %d characters.\n", chapters_count);

/* 
* Calculate the memory being used by the pointer array.
* Pointer size plus number of characters plus 5 (for 
* the \0). Determinining the amount of actual memory
* being used by the pointer array requires a little math 
* and some understanding of how C works. To start with, 
* the sizeof(chapters_ptr) chunk will return the memory
* used for the pointers themselves, which we know is 
* 20 bytes. To this, we add the previously determined
* characters count, since each character being stored
* requires 1 byte. Finally, 5 more butes are added, 
* representing the terminating \0 characters for each
* string which were not counted by strlen().
*/

ptr_count = sizeof(chapters_ptr) + chapters_count + 5;

/*
* Print that result.
*/

printf("The chapters_ptr array actually uses %d bytes of memory.\n", ptr_count);

/*
* End of main function.
*/

getchar();
return 0;

}