CITS2002 - Lecture 15
System-Calls, Structures and File Systems - Slides
System Calls & System- Defined Structures
- @ A system call is a controlled request from a user program to the OS kernel to perform a task that the program cannot do directly
- Most system calls accept integers and pointers to characters as parameters, and return an integer to indicate success or failure
- When more complex data is needed, structures are used defined in system header files
- e.g.
<time.h>,<sys/stat.h>
- e.g.
Accessing Structures via Pointers
- Normally to access fields of a structure we use a dot:
structure.field - When using pointers to structures, use the arrow operator
->
struct tm *tm = localtime(&NOW);
printf("%i/%i/%i", tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900);Accessing System Data
- The
/etc/passwdfile historically stores local user info - Programs can access it through system-provided structures and functions like:
{C}struct passwd *getpwent(void)
Defining Our Own Datatypes
- Use
typedefwithstructto define custom types for clarity and reusability:
typedef struct {
char teamname[31];
int played;
} TEAM;
TEAM team[MAX_TEAMS];- Access using
->if using pointers:
TEAM *tp = &team[t];
printf("%s %d\n", tp->teamname, tp->played);Grouping Related Data into Structures
- Instead of using parallel arrays, group related variables into a single structure:
typedef struct {
char *stopid;
char *name;
int metres;
} VIABLE;
VIABLE *home_stops = NULL;
VIABLE *dest_stops = NULL;Investigating Files - Using stat()
- The POSIX function
stat()retrieves file attributes stored in astruct stat:
struct stat stat_buffer;
stat(filename, &stat_buffer);
printf("Size: %d\n", (int)stat_buffer.st_size);- Can determine if a path is a file or directory:
if S_ISREG(stat_buffer.st_mode) -> file
if S_ISDIR(stat_buffer.st_mode) -> directory- This is important as there are differences between the code needed to open and read a text file, versus opening and reading a directory
Reading Directory Contents
- Open and read directories like files using:
DIR *dirp = opendir(dirname);
struct dirent *dp;
while((dp = readdir(dirp)) != NULL)
printf("%s\n", dp->d_name);
closedir(dirp);- These are POSIX functions, not part of C11
Combining readdir() with stat()
- To find whether each directory entry is another directory or file:
sprintf(fullpath, "%s/%s", dirname, dp->d_name);
stat(fullpath, &stat_buffer);
if(S_ISDIR(stat_buffer.st_mode)) ...
else if(S_ISREG(stat_buffer.st_mode)) ...