Hi folks,
Some years now since I was in involved with C-programming and now I just hit a pointer problem which a cannot figure out how to solve....
My problem is that I have to pass two file handles to a function which takes void* as parameter. (Nothing I can do about that.)
I've written a small stand-alone program to show the issue. I just cannot get the file handles back and use them in the function. Any hints?
/Andy
Code:
#include <stdio.h>
#include <stdlib.h>
void my_func(void* par1)
{
//how to do this part?!?!?
FILE* f1_p=(FILE*) (par1);
FILE* f2_p=(FILE*) (par1+4);
printf( "f1_p=0x%x\n",(uint) f1_p);
printf( "f2_p=0x%x\n",(uint) f2_p);
//this call generates a segmentation fault if the file handle isn't ok
long filepos=ftell(f1_p);
return;
}
int main(void) {
FILE *f1;
FILE *f2;
char* outputFileNameStr="testfile";
printf("!!!Hello World!!!\n");
//Open up the first file for writing
char file[256];
strcpy(file, outputFileNameStr);
file[strlen(outputFileNameStr)] = '\0';
f1 = fopen(file, "w");
printf( "%s\n",file);
//reuse the file-varaible again -- create a second file
file[strlen(outputFileNameStr)] ='_';
file[strlen(outputFileNameStr)+1] ='w';
file[strlen(outputFileNameStr)+2] ='s';
file[strlen(outputFileNameStr)+3] ='\0';
printf( "%s\n",file);
f2 = fopen(file, "w");
//both these open files should be passed to a function as a void*
//HOW TO DO THAT
//try to add them in an array so pointers to them are after each other in memory
FILE* fileHandle_arr[2];
fileHandle_arr[0]=f1;
fileHandle_arr[1]=f2;
printf( "f1=0x%x\n",f1);
printf( "f2=0x%x\n",f2);
printf( "&filehandle_arr[0]=0x%x\n",(uint) &fileHandle_arr[0]);
printf( "&filehandle_arr[1]=0x%x\n",(uint) &fileHandle_arr[1]);
//cast the array to a void_ptr since the function is defined that way
void* void_ptr= &fileHandle_arr[0];
my_func(void_ptr);
printf("Closing files\n");
fclose(f1);
fclose(f2);
return EXIT_SUCCESS;
}