CSPP 51081 - Tutorial #7

Files for today : tut7.zip

A dynamic stack data structure using malloc

A stack is a "first-in, last-out" (FILO) data-structure.
Today we will look at a sample implementation of a stack using dynamic memory allocation

ex1_stack.c   Text
ex1_stack.h   Text
ex1_driver.c   Text

Why is malloc useful in this example?

Is there a memory leak here?

Exercises:

Write a delete_stack method for this data structure. Be sure to free all memory.

Write a pop_n method for this data structure, that removes N items at once.

Another stack example: Resizing memory with realloc

realloc resizes a block of memory already allocated by malloc.

  void *realloc(void *ptr, size_t size);

Note that realloc returns NULL if the request fails.

Here we will look at another dynamic stack data structure, using realloc instead of malloc

ex2_stack.c   Text
ex2_stack.h   Text
ex2_driver.c   Text

File I/O library functions

In Tutorial 3 we saw how we can do File I/O using system calls, such as open and creat.
We will now look at file I/O using library functions.
 

We can also open a file using the C standard library function, fopen: To read or write to a file, we will use a FILE pointer. (FILE is a struct, but we don't need to worry about it's members).

To open a file, we use the fopen function.

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

Example:

if ( (fp = fopen("/home/wax/myfile.txt","r")) == NULL) {
  printf("Error: can't open file");
  ...
}

Note the use of error checking above. fopen returns NULL when the file is not found

Files are opened in one of three modes: read, write, or append.

ex3_libIO.c   Text

Formatted file input and output

We can use fprintf and fscanf in the same way that we use printf and scanf with standard out.
In function mycat2, observe how we use fprintf with stdout.

Character input and output

We can use getc and putc to read/write a single character from a file stream.

 while ( (c=getc(fp)) !=EOF)
 {
  putchar(c);
 }

We can also use fgets and fputs to read/write from the file by line rather than character.

Remember that error checking will be very important when working with files.

Direct File Input and Output

We use fread and fwrite to read/write to files in binary mode. ex3b_direct.c   Text

static variables

The static keyword has two purposes:

static can be used to extend the lifetime of an internal variable:

ex4_static.c   Text

The initialization :

 static unsigned int count = 0;

only occurs the first time the function is called.

static can be used with a function or global variable, to limit the scope to the file where it is declared.

ex5_static.c   Text
ex5_driver.c   Text