Reading in files as int/float array or one String/char[] ( OpenGL Data )

bearophile bearophileHUGS at lycos.com
Mon Dec 12 02:45:27 PST 2011


ParticlePeter:

>   auto fileFrag = cast( GLchar[] )readText( "Shader/Shader_01.frag" ) ;
>   const GLchar * fragSource = cast( GLchar * )fileFrag ;

Avoid raw casts every time it is possible. The second cast is not necessary, using the ".ptr".


> I use a dynamic array, and append each line to my array, which I think is not the most clever or efficient approach:

Try std.array.appender.


> 3.) When reading a file line by line it would be nice to have the count of Lines of the file ( numLines ) and the line number in a variable, so I could random access a fixed size array with this line number.

Fixed-sized arrays are often not good if you need to put lot of data inside them, because the stack has limited space (unless you allocate the fixed sized array on the heap).


> Can I get all floats ( words as float ) from a file at once without using file.byLine into a Dynamic array ( or fixed array, I know the word count ) ? 

In theory std.conv.parse is useful for this:

import std.stdio, std.conv;
void main() {
    string s = "[[1,2],[3,4]]";
    auto p = parse!(double[][])(s);
    writeln(p);
}

In practice the signature of one parse overload is:
Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ','); 

lbracket is a char instead of being a string, so I don't know how to parse a row that lacks commas and brackets. This seems an enhancement request.


> How can I get the Line count from a file,

You probably need to just iterate the file lines, and count them.


> and how can I get the line numbers without initializing a counter in front of the foreach loop and increase it manually inside the loop ?

With walkLength:


import std.stdio, std.range;
void main() {
    immutable size_t nLines = walkLength(File("data.txt").byLine());
    writeln(nLines);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list