I have followed this tutorial to implement a program that generates up to 100,000 random numbers and inserts them in a file to be sorted, but I have noticed that the loop with getw
is outputting way less numbers than expected. In my machine, this code only prints 49 numbers:
#include <stdio.h>
#include <stdlib.h>
int gen_random_file(int n_values) {
int index;
int num, num_count = 0;
FILE *r_file;
r_file = fopen("random_numbers", "w");
if (r_file != NULL) {
printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
return -1;
}
for (index = 0; index < n_values; index ) {
putw(rand(), r_file);
}
fclose(r_file);
r_file = fopen("random_numbers", "r");
// display numbers
printf("\nNumbers:\n");
while ( (num = getw(r_file)) != EOF ) {
printf("%d\n", num);
num_count ;
}
printf("\nEnd of file.\nNum Count = %d\n", num_count);
fclose(r_file);
return 0;
}
int main()
{
gen_random_file(10000);
return 0;
}
CodePudding user response:
You terminate the loop too early. rand()
is likely to produce -1
once in a while.
Quoting man getw
(section Bugs):
Since EOF is a valid integer value, feof(3) and ferror(3) must be used to check for failure after calling getw().
You need something like
while(1) {
if ((w = getw()) == EOF) {
if (feof(stdin) || ferror(stdin)) {
break;
}
printf(....);
....
}
// Deal with error if necessary
CodePudding user response:
This one of those rare cases where you actually want feof
. You need a loop like
while ((num = getw(r_file)), !feof(r_rile)) {
to read a number and then test for EOF.
On some systems (such as Windows), you'll also need "wb"
and "rb"
for your fopen modes to get a binary file.
CodePudding user response:
I ended up using fwrite
and fread
as well as "wb"
and "wr"
as parameters for fopen and that solved the problem.
#include <stdio.h>
#include <stdlib.h>
int gen_random_file(int n_values) {
int index;
int rand_num, num_count = 0;
int buffer[100000];
FILE *rand_file;
rand_file = fopen("random_numbers", "wb");
if (rand_file != NULL) {
printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
return -1;
}
for (index = 0; index < n_values; index ) {
rand_num = rand();
fwrite(&rand_num, sizeof(rand_num), 1, rand_file);
}
fclose(rand_file);
rand_file = fopen("random_numbers", "rb");
// display numbers
printf("\nNumbers:\n");
fseek(rand_file, 0, SEEK_SET);
fread(buffer, sizeof(rand_num), n_values, rand_file);
for (index = 0; index < n_values; index ) {
rand_num = buffer[index];
printf("%d\n", rand_num);
num_count ;
}
printf("\nEnd of file.\nNum Count = %d\n", num_count);
fclose(rand_file);
return 0;
}
int main()
{
gen_random_file(10000);
return 0;
}
CodePudding user response:
Perhaps this example is for linux, if you write code in Windows, you need to specify the wb flag in fopen