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.
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
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.
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.
static can be used to extend the lifetime of an internal variable:
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.