tags:

views:

1362

answers:

2

I'm trying to write some STL data out of matlab and I'm trying to do this by writing a MEX File (a matlab DLL written in C) At the moment I have a loop just going through my data writing out the stl syntax with the floats.

...

for(m=0;m<colLen;m++)
{

    res = m % 3;
    if(res == 0)
    {   
        fprintf(fp, "\tfacet normal %f %f %f \n",
                normalValues[(x*nvcolLen)+0], normalValues[(x*nvcolLen)+1], normalValues[(x*nvcolLen)+2]);
        fprintf(fp,"\t\touter loop\n" );
        flag = 0;
        x++;
    }


    fprintf(fp, "\t\t\tvertex ");

    for(n=0;n<rowLen;n++)
    {
        fprintf(fp, "%f ", xValues[m*rowLen+n]);

    }

    fprintf(fp,"\n");

    flag++;

    if (flag == 3)
    {
        fprintf(fp, "\t\tendloop\n\tendfacet\n");
        flag = 0;
    }

}

...

The main reason why I want to do this in a MEX file is because things are way quicker since its compiled. I was reading a C++ book, "Sams Teach Yourself C++ in One our a day" and in page 645 they talk about using a buffers to speed up writing to the disk. Once the buffer fills up, write the data, flush it, and do it again. They don't really show any code on how to do that and this is with C++'s streams.

How would I approach this in C? Would I just make a char* buffer with a fixed size, and then somehow check when its full and write it to a file with fwrite(), flush it, start over??

+1  A: 

fprintf does buffered output automatically for you. If there is a problem, show us the code that opens the file (fp).

jdigital
+1  A: 

Basically, of you want to do it yourself, you'd do it almost exactly as you wrote: Make a char* buffer, track the number of chars in it (by counting the chars you put in it) and if it is full (or nearly-full), flush it to the file.

However, this should really not be an issue with C streams, as they usually do buffering. You can even control this buffering with the function setbuf et al.

jpalecek