Writing large quantity of integers in a txt file in c

76 Views Asked by At

I wrote this code where I generate random integers in a large quantity and store them in a txt file. it works if I input up to 49 integers

1

but after that it does not read any further from the file or the file don't accept any further I don't know please help me

2

this is the code

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

int main(void)
{
    FILE *fptr;

    int num, n;

    fptr = fopen("integers.txt", "w");

    if (fptr != NULL)
    {
        printf("File created successfully!\n");
    }
    else
    {
        printf("Failed to create the file.\n");
        return -1;
    }

    printf("Enter some integer numbers [Enter -1 to exit]: ");
    scanf("%d", &n);
    while (n != 0)
    {
        num = rand();
        putw(num, fptr);
        n--;
    }

    fclose(fptr);

    fptr = fopen("integers.txt", "r");

    printf("\nNumbers:\n");
    int count = 0;
    while ((num = getw(fptr)) != EOF)
    {
        printf("%d\n", num);
        count++;
    }

    printf("\nNumber of elements in the file %d",count);
    fclose(fptr);

    return 0;
}
1

There are 1 best solutions below

0
Jabberwocky On

You have following problems:

  • As you're writing binary data, the file needs to be opened with "wb" and "rb" (b stands for binary). Othwerwise certain unwanted text substitutions will take place.
  • If one of your random numbers turns out to be -1, the read will stop prematurely because EOF has the value -1. Therefore you need to do the end of file check with the feof function instead of comparing the value read with EOF.
 fptr = fopen("integers.txt", "wb");   // <<< open with binary mode "wb"

 ...

 fptr = fopen("integers.txt", "rb");   // <<< open with binary mode "rb"

  printf("\nNumbers:\n");
  int count = 0;
  while (1)
  {
    num = getw(fptr);

    if (feof(fptr))   // end of file reached => stop the loop
      break;

    printf("%d\n", num);
    count++;
  }

BTW:

The documentation of getw concerning the return value is pretty misleading, especially the part "A return value of EOF indicates either an error or end of file" seems wrong to me. getw can read -1 values (0xffffffff) without problems.