I've been developing in C for a while now, coming from object-oriented languages like C++ and Java, and whilst using standard library functions like fread()
and strtok()
, I began to wonder: How do these functions go about storing variables related to their state?
For example, strtok()
behaves differently for subsequent calls, and fread()
keeps track of your position in the file. This information has to be stored somewhere, and in an object-oriented language there are scope constructs such as private
or protected
to guard these values from unwanted modification, but as far as I understand C does not have these.
So then, how are they safely stored? Or are they in fact global and modifiable from anywhere? The question spawned when I was writing a header file with utility functions that needed to store similar state information. What is the "right" way to do this sort of thing in C, and how is it handled in existing libraries?
C libraries store files in object code; during the linking phase of the compilation process ( Compilation Process) files in object code are accessed and used. It is faster to link a function from a C library than to link object files from a separate memory sticks or discs.
The C standard library provides macros, type definitions and functions for tasks such as string handling, mathematical computations, input/output processing, memory management, and several other operating system services.
ANSI Standard. The ANSI C standard library consists of 24 C header files which can be included into a programmer's project with a single directive. Each header file contains one or more function declarations, data type definitions and macros. The contents of these header files follows.
In the case of fread() the state is stored in a FILE structure. The structure is a resource allocated by fopen()
which returns a pointer to it, and you pass that pointer to every file operation call. The resource is released when fclose()
is called. The FILE resource may be allocated from a static pool or it may be dynamically allocated from the heap - that would be implementation dependent. For example:
RESOURCE* getResource()
{
return malloc( sizeof(RESOURCE) ) ;
}
int useResource( RESOURCE* r )
{
return r.index++ ;
}
void releaseResource( RESOURCE* r )
{
free( r ) ;
}
strtok()
on the other hand contains an internal static pointer that is initialised when a string is passed and used as the starting point when a null pointer is passed.
For example:
int getState()
{
static int state = 0 ;
return state++ ;
}
int main()
{
int s ;
do
{
s = getState() ;
printf( "state = %d\n", s ;
} while( s < 10 ) ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With