vendredi 7 juin 2019

Problem with reading numbers from file in C and generating MORE random numbers

I'm facing two problems at the moment. One of them is less important and is more related towards more random numbers than usual and the other one being why I can't successfully read numbers from a file.

Below are the two tasks:

Task A: Produce N random numbers in the range of 0-999 and save them to a file.

Task B: Read the numbers from the file and print them to the command line.

Problems:

A) While implementing Code A I get an infinite amount of the same number on my command line which happens to be the LAST number in the file. Implementation of Code B offers as many numbers in the command line as there are in the actual file but they all represent, like in the first case, the last number of the file. That happens to be my main problem, how can I fix it and why does this behavior occur?

B) Is there a better implementation of my srand function in order to produce more random numbers?

Code A

         ...
    i = 1;
    while (!feof(fp))
    {
        fread(&x, sizeof(x), 1, fp);
        printf("No.%d: %d \n", i, x);
        i++;
    }
         ... 

Code B

         ...
    i = 1;
    while (i <= N)
    {
        fread(&x, sizeof(x), 1, fp);
        printf("No.%d: %d \n", i, x);
        i++;
    }
         ... 

Full code:

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

int main()
{
    FILE *fp;
    char filename[100];
    printf("\n Enter the file's path: ");
    gets(filename);

    fp = fopen(filename, "w");
    if (!fp)
    {
        printf("\n An error occurred while trying to create the file. \nExiting the program... \n");
        return -1;
    }

    int N, i, x;

    printf("\n Enter the amount of numbers to be printed to the file: ");
    scanf("%d", &N);

    srand(time(NULL));
    for (i = 1; i <= N; i++)
    {
        x = rand() % 1000;
        printf("x = %d\n", x); // <========== TEST
        fprintf(fp, "%d\n", x);
    }

    // extra feature
    printf("\n %d numbers have successfully been added to the file. \nProceeding to show the numbers: \n", N);
    fseek(fp, 0, SEEK_SET);

    i = 1;
     while (!feof(fp))
    //while (i <= N)
    {
        fread(&x, sizeof(x), 1, fp);
        printf("No.%d: %d \n", i, x);
        i++;
    }

    fclose(fp);
    return 0;
}





Aucun commentaire:

Enregistrer un commentaire