Hi All,
I want to write a generic function which takes in a void pointer and length as input and writes the data referenced by the pointer to a file.
Another generic function which takes in a void pointer, length and offset and reads back the data to the memory referenced by the void pointer from the file.
Is it possible in C?
As fprintf needs the datatype to be specified, how can I achieve doing this? Is there any work around?
Thanks a lot for your time.

Thanks for the reply :)
Can fwrite & fprintf be used on the same file? If I want to write an integer followed by the data referenced by the pointer, is it possible?
I went through the example code of fwrite & it acts upon a file opened in "wb" mode. So can the same FILE pointer be used by fprintf. Something like this
fprintf of a string, followed by fwrite of a few bytes & again followed by fprintf and so on...
The same with reading. fscanf of the string followed by fread of a few bytes & so on...
I understand that I can write the code and check it out. But I am worried that even if it works & if I am doing something wrong, the code might fail in another platform.

Hi,
I tried this code

#include <stdio.h>
#include <stdlib.h>
int main() {
	FILE *fp;
	int i = 10;
	void *ptr, *ptr_r;
	double x[10], y[10];
	char ch;
	for(i = 0; i < 10; i++) x[i] = 2.0 * i;
	ptr = (void *)x;
	ptr_r = (void *)y;
	fp = fopen("raghu.dat", "wb");
	fprintf(fp, "%d\n", i);
	fwrite(ptr, 1, 10 * sizeof(double), fp);
	fclose(fp);
	fp = fopen("raghu.dat", "rb");
	fscanf(fp, "%d", &i);
	printf("%d\n", i);
	fread(ptr_r, 1, 10 * sizeof(double), fp);
	for(i = 0; i < 10; i++) printf("%lf\n", y[i]);
	fclose(fp);
	return(0);
}

Its able to print the value of i as 10, but y has all the values to 0.0.
Can anyone tell me what is wrong in this?

Off the top of my head, I suspect that the fscanf is reading too many or not enough bytes.

I recommend that you either treat the whole file as binary or treat the whole file as ASCII.

Where you do fprintf(fp, "%d\n", i) and fscanf(fp, "%d", &i) you could just as easily use fwrite(&i, 1, sizeof(i), fp) and fread(&i, 1, sizeof(i), fp) . The amount read/written would be far more consistent.

Hi Murtan,
Thanks for your reply. I was able to get the previous code working by changing the
fprintf(fp, "%d\n", i);
to
fprintf(fp, "%d", i);
without \n.
But what you said was right. This will create problems if I use fprintf & fscanf on strings.
I had one doubt in your reply.
fread & fwrite take void pointers, Is it ok to pass the &i, which is declared as integer?

Yes, functions that take a void * will accept any pointer type as they have no expectations of the pointer.

This article has been dead for over six months. Start a new discussion instead.