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

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

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;
}
You have following problems:
EOFhas the value -1. Therefore you need to do the end of file check with thefeoffunction instead of comparing the value read withEOF.BTW:
The documentation of
getwconcerning 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.getwcan read -1 values (0xffffffff) without problems.