Find the oldest or newest DateTime filename in a directory

	DIR *directory1;
	struct dirent *entry1;
	string filename;
	string filename_name;
	string filename_extension;
	uint64_t this_file_value;
	uint64_t selected_file_value;
	string selected_file_name;
	stringstream ss1;
	
	//This function looks for the oldest or newest filename, our filenames that are created using YYYYMMDDHHMMSS.extension format so it simply
	//converts their names to numeric and does a compare

	printf("Starting work through directory for next livedata file...\n");
	//selected_file_value = 0xffffffffffff;				//<Use for oldest file
	selected_file_value = 0;					//<Use for newest file
	directory1 = opendir("/home/pi/myfolder");			//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);
				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);

					if (filename_extension.compare(".txt") == 0)		//0=strings are the same
					{
						//We have: "2015092110" & ".extension"
						//We want: 2015092110

						printf("File: %s\n", filename_name.c_str());

						ss1.clear();
						ss1.str(std::string());
						ss1 << filename_name;
						ss1 >> this_file_value;
						if ((this_file_value > 0) && (this_file_value > selected_file_value))			//<<<Oldest or newest check here
						{
							//This file is older/newer than any previously found
							selected_file_value = this_file_value;
							selected_file_name = filename_name;
							printf("New selected file: %s\n", selected_file_name.c_str());
						}
					}
				}
			}

		}
	}
	closedir(directory1);

	if ((selected_file_value == 0xffffffffffff) || (selected_file_value == 0))
	{
		//-------------------------
		//----- NO FILE FOUND -----
		//-------------------------
		printf("No valid filename found - exiting\n");
		return(0);
	}
	
	//We have:
	//	selected_file_name			//Filename without the extension
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 *