Directory Locations

Referenced from root

Use “/”, e.g. “/home/pi/my_directory_name”

Create Directory If It Doesn’t Exist

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
	
	//----- CREATE DIRECTORY IF IT DOESN'T EXIST -----
	int result;
	extern int errno;
	struct stat sb;
	const char *directory_name = "/home/pi/my_directory_name";

	result = stat(directory_name, &sb);
	if ((result != 0) || !(sb.st_mode & S_IFDIR))
	{
		if (errno == ENOENT)		//ENOENT=No such directory entry
		{
			printf("The directory does not exist. Creating new directory: %s\n", directory_name);
			// Add more flags to the mode if necessary.
			result = mkdir(directory_name, S_IRWXU);
			if (result != 0)
			{
				printf("mkdir failed; errno=%d\n",errno);
			}
		}
	}

List contents of a directory

#include <dirent.h>

	DIR *directory1;
	struct dirent *entry1;

	directory1 = opendir(DB_FILEIO_DIRECTORY_LIVE_UPDATES_NOT_ACKNOWLEDGED);			//Open a directory stream
	if (directory1 != NULL)
	{
		while (entry1 = readdir(directory1))
		{
			if (entry1->d_type == DT_REG)			//DT_REG=regular file, DT_DIR=directory
			{
				printf("File: %s\n", entry1->d_name);
			
				//Getting separate filename and extension:
				/*
				string filename;
				string filename_name;
				string filename_extension;
				filename = entry1->d_name;
				size_t dot = filename.find_last_of(".");
				if (dot != std::string::npos)
				{
					filename_name = filename.substr(0, dot);
					filename_extension  = filename.substr(dot, filename.size() - dot);
				}
				else
				{
					filename_name = filename;
					filename_extension  = "";
				}
				printf("  Filename: %s\n", filename_name.c_str());
				printf("  Extension: %s\n", filename_extension.c_str());
				*/
			}
			
		}
	}
	closedir(directory1);
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *