function to write binary data to file

This is my first function which I do to write data which are saved in binaries array and I want them to save them e.g. in files like 1.bin, 2.bin or possibly kernel_1.bin, kernel_2.bin and so. I am stucked with the problem how to name the file. Possibly error may be on these two lines:
1
2
char * fname;
fname = (char)n+1;

I also tried
 
char fname[] = (char)n; 

where I got error.

May you help to finish this to success full finish? Any errors or mistakes I did?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void writeBinaries(char ** binaries, size_t * binary_sizes, size_t nDevices)
{
    char str[1000];
    int n; int pos = -1;
    for( n = 0; n < nDevices; n++ )
    {
        if( binary_sizes[n] != 0 )
        {
        char * fname;
        fname = (char)n+1;
        strcpy( fname, ".bin" );
        FILE* f = fopen(fname, "wb");
        fseek(f, pos, SEEK_SET);
        pos = pos + binary_sizes[n] + 1;
        int i;
        fwrite(binaries[n], binary_sizes[n], 1, f);
        fclose(f);
        }
    }
}
fname is a pointer. Pointer is a variable that holds a memory address as its value. Is n+1 an address?

Is it an address of an allocated memory block, where you can copy values to?
That is not what I want. But if I try
1
2
char fname[] = "";
fname = (char)n+1;

also I have error
incompatible types when assigning to type 'char[1]' from type 'int'|

I am trying to get the int n to char.

I am also unsure about the fwrite, should I use
fwrite(binaries[n], binary_sizes[n], 1, f);
or
fwrite(binaries[n], 1, binary_sizes[n], f);
?
Last edited on
char fname[] = "";
How many elements is in the array fname?

You want to convert a number into a C-string. http://www.cplusplus.com/reference/cstdio/sprintf/

http://www.cplusplus.com/reference/cstdio/fwrite/
Thanks.

I got this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void writeBinaries(char ** binaries, size_t * binary_sizes, size_t nDevices)
{
    char str[1000];
    int n; int pos = -1;
    for( n = 0; n < nDevices; n++ )
    {
        if( binary_sizes[n] != 0 )
        {
        char fname [50];
        sprintf (fname, "kernel_%d.bin", n+1);
        FILE* f = fopen(fname, "wb");
        pos += 1;
        fseek(f, pos, SEEK_SET);
        pos = pos + binary_sizes[n];
        int i;
        fwrite(binaries[n], binary_sizes[n], 1, f);
        fclose(f);
        }
    }
}

and as result fname is:
"kernel_1.bin\000|\000\000\035\002¸Ű\035\002`\000\000@dw’|\000\000\035\002@\bŰ\003`\000\000@\377\377\377\377dw’|"
I use the code blocks but I think this is all right because the \000 finishes the string.
Last edited on
Topic archived. No new replies allowed.