C Directory Tutorial

A common thing beginners want to know is how to handle directories in C. The C standard does not provide any way to do this, but it can be achieved using the C POSIX Library.

Reading Directory Contents

In this first section, you will be shown how to read the contents of a directory.

Headers and Types

First, include the following header file:

#include <dirent.h>

There are a few types you need to familiarize yourself with when working with directories. First type:

DIR

The DIR type represents a directory stream. It is usually passed to functions as a pointer. Second type:

struct dirent

This represents the current position in a directory stream. Depending on your environment, struct dirent can have many members, but the only one we're interested in now is:

char d_name[]

This is the name of the current file.

Functions

Now that you know the types, you can use functions in order to obtain them.

DIR* opendir(const char*)

opendir() opens a directory stream. It takes the directory name as it's only argument and returns a pointer to DIR. opendir() returns NULL when it has an error.

struct dirent* readdir(DIR*)

readdir() reads the directory stream provided as the first argument, and it returns a pointer to a dirent struct. It returns NULL after reading the directory stream.

int closedir(DIR*)

closedir() closes the directory stream provided in the first argument. It returns -1 when it has an error.

Code Example

ls.c
/* This program lists directory contents */
 
#include <stdio.h>
#include <dirent.h>
 
int main(int argc, char **argv) {
	char *dirname;
	DIR *dir;
	struct dirent *dp;
	/* read the first argument as the
	 * directory name to list, the default
	 * is to list the current directory */
	if (argc<=1) {
		dirname=".";
	} else {
		dirname=argv[1];
	}
	/* Open directory */
	dir=opendir(dirname);
	if (dir==NULL) {
		perror("Error opening directory");
		return 1;
	}
	/* List directory contents */
	while ((dp=readdir(dir))!=NULL) {
		/* Remember, d_name is the name of the current file */
		printf("%s\n", dp->d_name);
	}
	/* Close the directory */
	if (closedir(dir)==-1) {
		perror("Error closing directory");
		return 1;
	}
	return 0;
}

Current Working Directory

This section will teach you how to get the full path name for the current working directory.

Headers

The only header file you will need for this is:

#include <unistd.h>

Functions

Likewise, there is only one function you will need:

char* getcwd(char*, size_t)

getcwd() takes two arguments. The first argument is a string that have the current working working directory written to it. The second argument is the size of the string. getcwd() will return the current working directory, and it will return NULL when there is an error.

Code Example

pwd.c
/* Prints the pathname of the current working directory */
 
#include <stdio.h>
#include <unistd.h>
 
int main(int argc, char **argv) {
	char cwd[512];
	if (getcwd(cwd, 512)==NULL) {
		perror("Could not resolve pathname");
		return 1;
	} else {
		printf("%s\n", cwd);
	}
	return 0;
}

Changing Directories

This section will show you how to change the current working directory.

Headers

Once again, all you need is:

#include <unistd.h>

Functions

int chdir(const char*)

chdir() takes the directory to change to as it's only argument. This function returns -1 on error.

Code Example

chdir.c
/* Change current working directory */
 
#include <stdio.h>
#include <unistd.h>
 
int main(int argc, char **argv) {
	if (argc>1) {
		if (chdir(argv[1])==-1) {
			perror("Error changing directory");
			return 1;
		}
	} else if (argc==1) {
		printf("Usage: %s <directory>", argv[0]);
		return 1;
	} else {
		return 1;
	}
	return 0;
}

Creating Directories

Headers

There are two headers you need to include:

#include <sys/stat.h>
#include <sys/types.h>

Functions

int mkdir(const char*, mode_t)

mkdir() takes two arguments. The first argument is the name of the directory to create. The second argument sets the file permission bits. If you don't know what to put for the second argument, 0755 is usually the best choice. mkdir() returns -1 on error.

Code Example

mkdir.c
/* Creates a directory */
 
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
 
int main(int argc, char **argv) {
	if (argc>1) {
		if (mkdir(argv[1], 0755)==-1) {
			perror("Error creating directory");
			return 1;
		}
	} else if (argc==1) {
		printf("Usage: %s <directory>", argv[0]);
		return 1;
	} else {
		return 1;
	}
	return 0;
}

Removing Directories

Headers

This is the only header you need:

#include <unistd.h>

Functions

int rmdir(const char*)

rmdir() takes the directory to remove as it's only argument. Note that rmdir() will only remove empty directories. If you want to removed filled directories, you must first delete all of the files they contain. rmdir() returns -1 on error.

Code Example

rmdir.c
/* Removes an empty directory */
 
#include <stdio.h>
#include <unistd.h>
 
int main(int argc, char **argv) {
	if (argc>1) {
		if (rmdir(argv[1])==-1) {
			perror("Error removing directory");
		}
	} else if (argc==1) {
		printf("Usage: %s <directory>", argv[0]);
		return 1;
	} else {
		return 1;
	}
	return 0;
}

Renaming Directories

Renaming directories is exactly the same as renaming files in C. Consequently, renaming directories is in the C Standard, and should work on all operating systems with conforming C compilers.

Headers

The only header needed is:

#include <stdio.h>

Functions

int rename(const char*, const char*)

rename() takes two arguments. The first argument is the file to rename. The second argument is what the file will be renamed to. rename() returns 0 on success, and nonzero on failure.

Code Example

rename.c
/* This program will rename a file or directory */
 
#include <stdio.h>
 
int main(int argc, char **argv) {
	if (argc>2) {
		if (rename(argv[1], argv[2])!=0) {
			perror("Error renaming");
			return 1;
		}
	} else if (argc==2||argc==1) {
		printf("Usage: %s <file> <renamedfile>", argv[0]);
		return 1;
	} else {
		return 1;
	}
	return 0;
}
 
c/directories.txt · Last modified: 2010/07/12 05:06 by guest
 
Except where otherwise noted, content on this wiki is licensed under the following license:Public Domain
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki