Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Does someone knows better C code for this?

Status
Not open for further replies.

perlguy

Programmer
May 17, 2001
26
US
Hi everyone.
Sorry to start this new thread , but had no choice since earlier thread was going too lengthy. With the help of some good experts in this forum I have come up with following solution for my following need:

File "list.txt" consist records as :
1=bill gates=MicroSoft
2=Sam walton=Walmart
3=Steve Jobs=Apple
4=Larry Ellison=Oracle

Now prg. should generate random number between 1 to 4 (since i am giving eg. of 4 records)and should print record details corr. to that number and will write the output in another file called 'list.out'. For example If it generates random no. 2 , it should read the file and print details of record that corr. to 2 in the following fashion:
Sam walton
Walmart
Then it should write above details in 'list.out' as below:
Name=Sam Walton=Company=Walmart

## SOLUTION: (very close but not 100% to the point)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
FILE *fp;
char *pch, cdata[200];
char recflag = 'N';
int number, rnd_number;
time_t t;

/* for random number */
srand( (unsigned) time(&t));
while((rnd_number = rand() % 5) == 0);
printf(&quot;RANDOM = %d \n&quot;, rnd_number);

fp = fopen(&quot;list.txt&quot;, &quot;r&quot;);
fscanf(fp, &quot;%d&quot;, &number);
while( !feof(fp))
fgets(cdata, 100, fp);
if(number == rnd_number)
{
printf(&quot;RECNO :: %d \n&quot;, number);
printf(&quot;DATA :: %s \n&quot;, cdata);
recflag = 'Y';
break;
}
fscanf(fp, &quot;%d&quot;, &number);
}
fclose(fp);
if(recflag == 'N') printf(&quot;\n Not Found !!&quot;);
if(recflag == 'Y')
{
/* perform splitting */
pch = strtok(cdata, &quot;=&quot;);
while (pch != NULL)
{
printf (&quot;%s\n&quot;,pch);
pch = strtok (NULL, &quot;=&quot;);
}
}

/* Don't know how to store above values in
other varibales so that I can write in 'list.out' */
/* can anyone do the rest ...... */

return 0;
}

The above prg. works fine and prints details the way i want,but the only problem is I want store these values in another tmp variables so that I can write it in 'list.out' file.
Please shed some thoughts on this. Can anyone come up with some good code for the above. Both logic wise and performance wise. I wnat this code to be very efficient and faster also error proof.

regards
perlguy.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top