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

Weird behaviour or array appending

Moderators: kris

Posted: 07/26/08 02:33:08

Take a look at the following code:

import tango.io.stream.TextFileStream;
import tango.io.Stdout;

import tango.io.FileConduit;

void main()
{
	auto f = new TextFileInput(r"c:\dmd\import\tango\text\locale\Data.d");
	auto a = new FileConduit("a.txt", FileConduit.WriteCreate);
	
	char[][] lines;
	foreach (line; f) {
		lines ~= line;
		a.write(line);
		a.write("\r\n");
	}
	f.close();
	a.close();
	
	auto b = new FileConduit("b.txt", FileConduit.WriteCreate);
	foreach (line; lines) {
		b.write(line);
		b.write("\r\n");
	}
	b.close();
}

Here is what it does: it opens a file, reads it line-by-line, writes line-by-line to soome other file (a.txt). It also appends the lines into an array lines. Next, we open other file (b.txt) and write the contents of the lines array line-by-line.

I expect the two resulting files to be same. In fact, they are the same for small files (<30 kb) and aren't for large ones. An order is somehow changed sometimes(!). Does the array contents get sorted, or what? Why is the order is changed? I don't get it :(

Author Message

Posted: 07/26/08 06:27:27

hehe ... the original line is actually sliced from an input buffer, so it not guaranteed to be valid beyond a second invocation (to get the next line). To hang onto the line, you should .dup it, or use some other mechanism.

Hope that help :)

Posted: 07/26/08 10:17:49

Yeah, right. Mutability is an evil :) Thank you.