9. Database

In this last chapter we will learn, how to create a database. First we must make a declaration for a structure:

#define ARRAY_SIZE 100
    /* Structure declaration */

    struct record{
        char name[21];
        char tel[15];
    };

    /* declaration of array of structure */

    struct record array[ARRAY_SIZE];/* max. 100 records*/

Next we must write the file by reading one record at a time.

i=0;
    fread (&array[i], sizeof(struct record),1, file); 
    while (!feof(file) && i<ARRAY_SIZE-1)
    {
        i++;
        fread (&array[i],sizeof(struct record),1, file);
        extern int nmb = i;/*nmb must be a global variable*/
    } 

After the array is ready to copy to the file, it can be done by using fwrite-function:
fwrite(array, sizeof (struct record), nmb, file) /*nmb is the number of records in array*/
Next example (written in finnish) shows, how program reads 10 integers in array, sorts them and after that prints them. This example doesn’t write the data into a file!

    #include<stdio.h>

    /* SYMBOLIC CONSTANTS*************/

    #define KOKO 10/*SIZE OF THE ARRAY*/

    /* PROTOTYPES FOR FUNCTIONS *********/

    void tayta_taulukko (void);/*fills the array*/
    void tulosta_taulukko (void);/prints the array*/
    void lajittele_taulukko (void);/*sorts the array*/
    void vaihda (int *, int *);/*swaps the numbers in ascending order)

    /* GLOBAL VARIABLES ************/

    int taulukko[KOKO];/*taulukko= array*/

    /* MAIN PROGRAM********************/

    void main (void)
    {
        tayta_taulukko();
        lajittele_taulukko();
        tulosta_taulukko();
    }

    /* FUNCTION DECLARATIONS***********/

    void tayta_taulukko (void)
    {
        int i;
        for (i=0; i<KOKO; i++)
        {
            printf ("Enter integer : ");
            scanf ("%d",&taulukko[i]);
        }
    }

    void tulosta_taulukko (void)
    {
        int i;
        for (i=0; i<KOKO; i++)
        {
            printf ("%d\n",taulukko[i]);
        }
    }

    void lajittele_taulukko (void)
    {
        int i,j,pienin;/* pienin=smallest*/
        for (i=0; i < KOKO-1; i++)
        {
            pienin = i;
            for (j=i+1; j < KOKO; j++)
            {
                if (taulukko[j] < taulukko[pienin]) 
                {
                    pienin = j;
                }
            }
            if (pienin != i)
            {
                vaihda (&taulukko[i], &taulukko[pienin]);
            }
        }
    }

    void vaihda (int *x, int *y)
    {
        int apu;
        apu = *x;
        *x = *y;
        *y = apu;
    }

Let’s continue with files. Next example shows how to copy one file to another.

/*reduce: copies one file */
#include 
main(argc, argv)
int argc; 
char *argv[]; 
{
	FILE *In, *Out;
	int charac;
	int number=0;
	static char name[20];

   if(argc < 2) 
    printf("I need a filename for argument\n");
  else 
  { 
     if ((In = fopen(argv[1], "r")) != NULL )
	 {
		 strcpy(name, argv[1]);
		 strcat(name,".red");
		 Out=fopen(name, "w");
		 while((charac=getc(In)) != EOF)
			 /*if(number++%3 ==0) what happens if you add this to your code?*/
			putc(charac,stdout);
		fclose(In);
		fclose(Out);
	 }
	 else
       printf("Cannot open file \"%s.\".\n", argv[1]);
  }   
}
Usage: type reduce file.txt in command prompt, file should contain some text.

Next example is a database, where the options 3 and 4 are missing. Your task is to write them.

/*Database: Usage of database */ 
#include <stdio.h>
#define NAME_MAX 20
main(number,names)  /*HERE STARTS MAIN*/
int number; 
char *names[]; 
struct record{
        char name[21];
        char tel[15];
  };
{ 
  struct record r;
  char line[81];
  FILE *In;
  char contacts[20];
  char answer;
  int selection;
  do{
  printf("\nDatabase program, please select:");
  printf("\n1. Add the data");
  printf("\n2. Print the data");
  printf("\n3. Update the data, not in use");
  printf("\n4. Remove the data, not in use");
  printf("\n0. Exit");
  printf("\nYour choice: ");
  scanf("%d", &selection);
  getchar();
  switch(selection)
  {
	 case 1: 
	 if(number < 2) 
		puts("I need a filename for argument\n");
		else 
		{ 
			if ((In = fopen(names[1], "wb")) == 0 )
			printf("Cannot open! %s.\n", names[1]); 
			else 
			{ 
				do{
					printf ("\nEnter the name (max %d characters):", NAME_MAX);
					gets(r.name); 
					printf("\nEnter the phonenumber: "); 
					gets(line);
					sscanf(line,"%d",r.tel);   
					fwrite(&r, sizeof r,1,In);   
					printf ("\nMore names (y/n)?");
					answer = getchar();
					getchar();
				}while (answer=='y');	
			}
			fclose(In);
		}
			break;
	 case 2: 
	 if(number < 2) 
		puts("I need a filename for argument\n");
		else
		{ 
			if ((In = fopen(names[1], "rb")) == 0 )
			printf("Cannot open! %s.\n", names[1]); 
			else 
			{ 
			fread (&r,sizeof r,1,In);
			while (!feof(In)) 
                {
                    printf ("\n%s %d\n",r.name,r.tel);                    
					fread(&r,sizeof r,1,In);
				}
			}
			fclose(In);
		}
			break;
	 case 0: 
	 printf("\nYou selected the exit, Goodbye."); 
	 break;
	 default: printf("\n Enter the right choice! (0, 1, 2)"); break;
  }
  }while(selection != 0);
}
Usage: Enter Database file.bin in command prompt.

This is a last chapter of C programming. Although we have dealt with many issues, there are a lot of things you can study more. For example recursion, the C preprocessor, miscellaneous functions, command line arguments etc. These issues you can study from the C Programming Language by Ritchie Kernigham. Hopefully you have enjoyed the course and specially learned a lot.

NOTE! This chapter  exercises can be found in quiz exercises to chapter 9 This information will be tested in quizzes 7-9 It is very important that the student will make all examples shown in this chapter.