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

user6419293 picture user6419293 · Jun 3, 2016 · Viewed 7.8k times · Source

So 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);
}

Answer

unwind picture unwind · Jun 3, 2016

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);
}