user6419293
user6419293

Reputation:

Generating Random Numbers in C and writing it to a text file

I've created a project that reads numbers from a text file and draws an isometric projection of it, but now I'm trying to create a program that generates numbers from 0-9 and writes them in the document. This is what my code looks like, but the document remains empty. I'm under the assumption that the error is either in my rand() function usage, or when I convert the integers to characters.

Thank you in advance for all the input, and I apologize if it's just an operator error. I'm pretty new to this stuff:

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

int     main(void)
{
    char    str[10];
    FILE    *fptr;
    int     i;
    int     num;
    char    num2;
    i = 0;

    fptr = fopen("map.fdf", "w");
    if (fptr == NULL)
    {
        printf("ERROR Creating File!");
        exit(1);
    }
    while (str[i] != '\0')
    {
        num = rand() % 10;
        num2 = num + '0';
        str[i] = num2;
        i += 1;
    }
    puts(str);
    fprintf(fptr,"%s", str);
    fclose(fptr);
    return (0);
}

Upvotes: 1

Views: 11401

Answers (3)

Arkzuse
Arkzuse

Reputation: 1

FILE *fn;
int num, n, range;

printf("Enter number of positive integer:");
scanf("%d", &n);
printf("Enter max integer:");
scanf("%d", &range);

fn=fopen("number.txt", "w");
for (int i=0; i<n; ++i) {
    num = (rand()%range) + 1;
    fprintf(fn, "%d\n", num);
}
fclose(fn);

Upvotes: 0

unwind
unwind

Reputation: 400029

I don't understand your while loop, it seems to wait for some condition that it doesn't contain code to make happen.

Anyway, how about not re-inventing how to convert single-digit integers to characters, and instead using higher-level I/O functions to just print to the file? That's why they're there, after all. :)

for (int i = 0; i < 10; ++i)
{
  fprintf(fptr, "%d", rand() % 10);
}
fprintf(fptr, "\n");  /* Probably nice to make it a line. */

If you really must make do without for, you can of course always manually transform it into a while loop:

int i = 0;
while(i++ < 10)
{
  fprintf(fptr, "%d", rand() % 10);
}

Upvotes: 3

Hans-Martin Mosner
Hans-Martin Mosner

Reputation: 856

Your "str" is uninitialized, but apparently has a '\0' character as it's first element, so the while loop does not execute.

Upvotes: 2

Related Questions