我已經按照本教程實作了一個程式,該程式生成多達 100,000 個亂數并將它們插入到要排序的檔案中,但我注意到回圈getw輸出的數字比預期的要少。在我的機器上,這段代碼只列印 49 個數字:
#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;
}
uj5u.com熱心網友回復:
您過早終止回圈。rand()很可能會偶爾產生-1一次。
參考man getw(部分錯誤):
由于 EOF 是一個有效的整數值,呼叫 getw() 后必須使用 feof(3) 和 ferror(3) 來檢查是否失敗。
你需要類似的東西
while(1) {
if ((w = getw()) == EOF) {
if (feof(stdin) || ferror(stdin)) {
break;
}
printf(....);
....
}
// Deal with error if necessary
uj5u.com熱心網友回復:
這是您真正想要的罕見情況之一feof。你需要一個回圈
while ((num = getw(r_file)), !feof(r_rile)) {
讀取一個數字,然后測驗 EOF。
"wb"在某些系統(例如 Windows)上,您還需要"rb"fopen 模式來獲取二進制檔案。
uj5u.com熱心網友回復:
我最終使用fwriteandfread以及"wb"and"wr"作為 fopen 的引數,這解決了問題。
#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;
}
uj5u.com熱心網友回復:
可能這個例子是針對linux的,如果你在windows下寫代碼,需要在fopen中指定wb標志
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505064.html
