C code... file reading(twice)... strange problem!

Rohit Kumar <rohitsz2-/[email protected]> Sat, 19 Mar 2005 04:54:59 -0800 (PST)
Newsgroups gmane.user-groups.linux.delhi.devel
Message-ID <[email protected]>
Greetings there,
i am getting strange result in the following code...
what i am doing in the code...

0.main
1.create a file
2.write numbers into it
3.close file

4.open file in read mode
5.read numbers written
6.close file

7.call a function
8.open file(same file)
9.read numbers
10.assign it to a pointer
11.close file
12 return pointer

13.print numbers from the pointer received in main
14.end-main


upto step 8 things are ok..
after that when i try to read the numbers from the
file, it always returns the last number that was
written to the file...
here goes the code...
-------------------------------------------------------
#include<stdio.h>

#define LT 10   /* 10 */

long* getRandomNumArray(long);

int main()
{

long i,*val;
FILE *fs;
long *li,*lb;

fs=fopen("temp.dat","w");

if(fs==NULL)
	{
		printf("Error opening file[w]\n");
		exit(0);
	}
else
{

	for(i=0;i<LT;i++)
	{
		val=&i;
		fwrite(&val,sizeof(long),1,fs);
		printf("%ld\t",*val);
	}

}
if(fs!=NULL)
	fclose(fs);


printf("\n");

fs=fopen("temp.dat","r");
if(fs==NULL)
	{
		printf("Error opening file[r]\n");
		exit(0);
	}
else
{
	for(i=0;i<LT;i++)
	{
		fread(&val,sizeof(long),1,fs);
		printf("%ld\t",*val);
	}

}
if(fs!=NULL)
	fclose(fs);

printf("\n");

	lb=getRandomNumArray(LT);
	li=lb;
	if(li!=NULL)
	{
	printf("printing number\n");
	for(i=0;i<LT;i++)
		printf("%ld \t",*li++);
	}
printf("\n");
return 0;
}/*main*/


long* getRandomNumArray(long n)
{
	long *base,*ptr,*val;
	long i; int p;
	FILE *fp;

	fp=fopen("p.dat","r");

	if(fp!=NULL)
	{

		ptr=(long *)malloc(n*sizeof(long));
		base=ptr;

		printf("\nin getRandomNumArray(long n)\n");
		if(base!=NULL)
		{

			for(i=0;i<n;i++)
			{
           /* fread reads same value every time!*/
				
                    fread(&val,sizeof(long),1,fp);
				if(p=fgetc!=EOF)
				printf("pooja %ld: %ldfget %d\n",i,*val,p);
				*ptr++=*val;
			}

		}
		else
		{
			printf("Cannot Allocate memory\n");
			free(ptr);
			free(base);
			base=NULL;
			ptr=NULL;
		}
		fclose(fp);
	
	}
	else
	{
		printf("Unable to open File...\n");
	
	}
	return base;
	
}


-------------------------------------------------------


kindly do tell what can i do to get over this problem.

thanks,
rohit.

NAMASTE, i honour the spirit in you which is also in me.
```````````````````````````````````````````````````````
http://www.geocities.com/rohitsz2

|Anytime you feel i need to understand| 
|a concept before i am eligible to get|
|an answer i would be happy to know.  |
^*************************************^


		
__________________________________ 
Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/resources/