Hey, I'm hoping someone can help out here. I'm trying to use the rand() function to generate sequential random numbers in C, and then write them to file. Now I know it's possible, I'm just not sure whether it is the way I want to do it. I have already used the rand function to generate numbers and write them to file, it's just the doing it in sequence that's being a big pain.
Now at the mo I've got this code:
#include <stdio.h>
#include <stdlib.h>
FILE *bptr; /* Pointer to file 'bptr' */
int i, j, k, n;
int main(void)
{
printf("\nOpening file bptr.txt for reading...\n");
if ((bptr = fopen("bptr.txt", "w")) == NULL)
{
printf("\nI won't open file cos there's an error\n");
exit(1);
}
else
{
printf("\nI've opened file cos you asked for it.\n");
}
/* For loop to generate 50 random numbers*/
for (i = 0; i < 50; ++i)
{
if (i % 14 == 0)
putchar('\n');
j = rand();
k = j; /* Assign random number generated to a variable*/
if (k > j) /* Attempt to check if random number generated is larger than previous, if it is then it gets printed to file, else it gets printed to screen */
{
fprintf(bptr, "\n%d\t", k);
}
else
printf("%7d\t", k);
/*if (i < j)
fprintf(bptr, "\n%d\t", j);
//printf("%7d", j);*/
}
/*for ( ; i < j; ++i)
{
j = k;
}*/
printf("\n");
printf("\nClosing text file...\n");
fclose(bptr);
return 0;
}
All it gives me is 50 integers printed out to the screen, and not even one printed to the file. What I am trying to do is to let rand run, and generate as many numbers as it needs to. Then if the number generated is larger than the previous number, then it should get printed to file, and wait for the next number generated by rand that is larger than it. Any ideas?
Cheers