Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Having trouble with associative array .keys property

Moderators: kris

Posted: 05/05/12 20:24:49

I find myself needing a bit of a hand. I have the following piece of code, which should iterate over every file in a directory, and add them to an associative array. However, it seems to print out garbage for the keys when I print them to console. The file is definitely there, and the name is correct up until I print out the keys

// for each file in path
foreach( file; new FilePath(path) ){
	// if it's a csv file
	if( !file.folder ){
		char[] name = file.name;
		if( file.name[file.name.length-4 .. $] == ".csv" )
			name = file.name[0 .. file.name.length-4];
		// add it to the tables
		tables[ name ] = new CSVFile;
		
		debug Stdout.formatln( "loading table named '{}'", name );
		
		tables[ name ].load( path ~ file.name );

		/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		/// !!!! UP TO THIS POINT, name IS SEEN AS 'sample' !!!!
		/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	}
}

debug{
	Stdout.formatln( "writing out tables found:" );
	foreach( key; tables.keys ){
		Stdout.formatln( "  {}", key );
	}
}

For the above section of code, I get the following console result;

loading table named 'sample'
writing out tables found:
  p     C ?>

where 'sample.csv' is the only file in the folder

Author Message

Posted: 05/10/12 19:55:41

Just a guess. I think the FilePath class will reuse the strings for the names. Try duping the string when storing it.

tables[name.dup] = new CSVFile;