This is very tough for me, but I did my great attempt to solve but FAILED !! It would be great if someone has good stong alternative for the below C prg. :
I am trying return a file record data from the function file_process() but it does not work properly. I mean everthing is ok inside function, It does print the correct value. But when I say return(cdata); I am getting junk chars along with a
warning: "unction returns address of local variable"
What is wrong with following code?
What is the best way to retun data.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* function prototype */
char file_process(char *flname, int rnd_num);
int main(void)
{
/* variable declaration */
FILE *out_bg;
char *temp, trdata[150];
temp = file_process("list.txt", 5);
strcpy(trdata, temp);
printf("Return Data = %s", trdata);
return 0;
}
char file_process(char *flname, int rnd_num)
{
/* variable declaration */
FILE *fp;
char cdata[150];
char recflag = 'N';
int rec_number, rnd_number;
time_t t;
srand((unsigned) time(&t));
rnd_number = rand() % rnd_num+1;
if ((fp = fopen(flname, "r") == NULL) exit(1);
fscanf(fp, "%d", &rec_number);
while( !feof(fp))
{
fgets(cdata, 150, fp);
if(rec_number == rnd_number)
{
recflag = 'Y';
break;
}
fscanf(fp, "%d", &rec_number);
}
fclose(fp);
if(recflag == 'N') exit(1);
if(recflag == 'Y')
{
printf("SP RANDOM = %d \n", rnd_number);
printf("RECNO :: %d \n", rec_number);
printf("DATA :: %s \n", cdata);
}
return(cdata);
}
I am trying return a file record data from the function file_process() but it does not work properly. I mean everthing is ok inside function, It does print the correct value. But when I say return(cdata); I am getting junk chars along with a
warning: "unction returns address of local variable"
What is wrong with following code?
What is the best way to retun data.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* function prototype */
char file_process(char *flname, int rnd_num);
int main(void)
{
/* variable declaration */
FILE *out_bg;
char *temp, trdata[150];
temp = file_process("list.txt", 5);
strcpy(trdata, temp);
printf("Return Data = %s", trdata);
return 0;
}
char file_process(char *flname, int rnd_num)
{
/* variable declaration */
FILE *fp;
char cdata[150];
char recflag = 'N';
int rec_number, rnd_number;
time_t t;
srand((unsigned) time(&t));
rnd_number = rand() % rnd_num+1;
if ((fp = fopen(flname, "r") == NULL) exit(1);
fscanf(fp, "%d", &rec_number);
while( !feof(fp))
{
fgets(cdata, 150, fp);
if(rec_number == rnd_number)
{
recflag = 'Y';
break;
}
fscanf(fp, "%d", &rec_number);
}
fclose(fp);
if(recflag == 'N') exit(1);
if(recflag == 'Y')
{
printf("SP RANDOM = %d \n", rnd_number);
printf("RECNO :: %d \n", rec_number);
printf("DATA :: %s \n", cdata);
}
return(cdata);
}