Operating Systems 2019F Lecture 4
Video
Video from the lecture given on Sept. 13, 2019 is now available.
Topics
- files
- open, read, write, close system calls
- I/O redirection
- command line arguments
- programmatic directory access
Notes
What can you do with a file normally? * open it <--- why? * read from * write to * close it <--- why? By having open and close, we tell the OS that - we're going to do multiple operations on this file, and - save the mapping of the filename to the underlying file data - do permission checks now, not when we access the file When you open a file, you get a file descriptor (a small int)
Code
filetest.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[], char *envp)
{
int fd;
char *msg = "Hello world!\n";
char *stdmsg = "Hello standard out!\n";
write(1, stdmsg, 20);
/* open a file */
fd = open("test.txt", O_CREAT|O_APPEND|O_WRONLY,
S_IRUSR|S_IWUSR);
printf("Got file descriptor %d\n", fd);
/* write something to the file */
write(fd, msg, 13);
/* close the file */
close(fd);
return 0;
}
dirtest.c
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
int main(int argc, char *argv[], char *envp[])
{
DIR *d;
struct dirent *entry;
if (argc > 1) {
d = opendir(argv[1]);
} else {
d = opendir(".");
}
entry = readdir(d);
while (entry) {
printf("Entry: %s\n", entry->d_name);
entry = readdir(d);
}
closedir(d);
return 0;
}