Brain Dump

Directory

Tags
comp-arch

Is a file-system entry that can contain a hierarchy of files.

Like files there are system calls provided to open, read and close directories, however there isn't a sys-call for writing to a directory (since that implies creating a file or a link).

Note: On UNIX the readdir function always includes . and .. for the current and parent directories. Warn: readdir is not thread-safe.

int exists(char *dir, char *name) {
    struct dirent *dp;
    int found = 0;
    DIR *dirp = opendir(dir);
    while ((dp = readdir(dirp)) != NULL) {
	puts(dp->d_name);
	if (!strcmp(dp->d_name, name)) {
	    found = 1;
	    goto finish;
	}
    }
finish:
    closedir(dirp);
    return found;
}
Code Snippet 1: A simple function to check whether a file with name exists in dir by listing all the files in dir.

Links to this note