Reputation: 804
i expect to have more than one million files with unique names. I have been told that if i put all this files in one or two directories the search speed for these files will be extremely slow. So i have come up with the following directory architecture.
I want the directory structure to branch out with 10 sub directories and the level of the sub directories will be 4. because the file names are guaranteed to be unique i want to use these file names to make hashes which can be used to put the file in a directory and also later to find it. The random hash values will make a directory to have,approximately, 1,000 files.
so if F is root directory then inserting or searching for a file will have to go through these steps:
I want to use numbers from 0-9 as directory names
h=hash(filename)
sprintf(filepath,"f//%d//%d//%d//%d//.txt",h%10,h%10,h%10,h%10);
HOW DO I CREATE THESE DIRECTORIES?
EDIT:
All the files are text files. The program will be distributed to many people in order to collect information for a research. So tt is important that these files are created like this.
EDIT:
i created the following code to implement perreal's pseudo code. It compiles to success but gives the run time error given at the end.
error occurs at the sprintf()
line.
#include<iostream>
#include<stdlib.h>
#include<windows.h>
void make_dir(int depth, char *dir) {
if (depth < 4) {
if (! CreateDirectoryA (dir,NULL))
for (int i = 0; i < 10; i++) {
sprintf(dir,"\\%d",i);
char *sdir=NULL ;
strcpy(sdir,dir);
CreateDirectoryA(sdir,NULL);
make_dir(depth + 1, sdir);
}
}
}
int main()
{
make_dir(0,"dir");
return 1;
}
Unhandled exception at 0x5b9c1cee (msvcr100d.dll) in mkdir.exe: 0xC0000005: Access violation writing location 0x00be5898.
Upvotes: 1
Views: 1017
Reputation: 98058
Kind of pseudo code, but can be done like this:
void make_dir(int depth, char *dir) {
if (depth < 4) {
CreateDirectoryA (dir,NULL);
for (int i = 0; i < 10; i++) {
char *sdir= (char*)malloc(strlen(dir+10)); // XXX 10?
strcpy(sdir, dir);
sprintf(sdir + strlen(sdir), "\\%d", i);
printf("%s\n", sdir);
//CreateDirectoryA(sdir,NULL);
make_dir(depth + 1, sdir);
free(sdir);
}
}
}
}
And to call make_dir(0, rootdir);
Upvotes: 2
Reputation: 16153
Do not do this:
sprintf(dir,"\%d",i);
dir
is a const, read only string in your example.Do not copy to sdir without allocating memory first.
sdir = (char *)malloc( strlen( dir ) + 1 );
At the end of the function make_dir
, you will have to call free( sdir );
so you do not leak memory.
Upvotes: 1