[英]Trouble with saving data to and reading from a file in c
按照標題,確實可以在程序運行且文件存在時將數據保存到文件中的代碼正常工作。 但是,在代碼的第二部分中,程序會編譯,但在運行時會因錯誤而停止。 在我發布代碼之前,我想對發布者表示感謝,因為我從該站點中學到了很多東西,但這是我第一次發布。
#include <stdio.h>
#include <stdlib.h>
int const MAX_SIZE = 1000000;
FILE *randomdata;
char outputFilename[] = "array.dat";
int main(void)
{
int i;
randomdata = fopen(outputFilename, "w");
for (i = 0; i < MAX_SIZE; i++)
fprintf(randomdata, "%lf\n", rand() * 1.0 / RAND_MAX);
return 0;
}
可以看出,第一段代碼創建了一個名為array.dat的文件,該文件存儲隨機數。
我假設第二個地方存在邏輯錯誤的意思是從array.dat中獲取數字,然后找出中值。
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000000
#include <time.h>
int main(void)
{
int left, right;
int pivot_index, store_index;
int i, k;
double tmp;
double a[MAX_SIZE];
double pivot_value;
double start;
double end;
FILE *f;
char inputFilename[] = "array.dat";
for (i = 0; i < MAX_SIZE; i++) {
f = fopen("array.dat", "r");
fscanf(f,"%lf", &a[i]);
printf("%lf", &a[i]);
}
k = MAX_SIZE / 2; /* the median position */
left = 0; right = MAX_SIZE;
start = clock();
srand(time(0));
while (left != k) {
pivot_index = rand() % (right -left) + left;
pivot_value = a[pivot_index]; /* swap (a[ pivot_index ],a[ right -1]) ; */
tmp = a[pivot_index];
a[pivot_index] = a[right - 1];
a[right - 1] = tmp;
store_index = left;
for (i = left; i < right - 1; i++) {
if (a[i] < pivot_value) { /* swap (a[ store_index ], a[i ]) ; */
tmp = a[store_index];
a[store_index] = a[i];
a[i] = tmp;
store_index++;
}
} /* swap (a[ right -1] , a[ store_index ]) ; */
tmp = a[right - 1];
a[right - 1] = a[store_index];
a[store_index] = tmp;
pivot_index = store_index;
if (k <= pivot_index) {
right = pivot_index;
} else {
left = pivot_index + 1;
}
}
end = clock();
printf("The program took %lf seconds\n", endstart / 1000000);
printf("Median is %lf\n", a[k - 1]);
return 0;
}
代碼中的問題肯定在我認為的以下部分中:
for (i = 0; i < MAX_SIZE; i++) {
f = fopen("array.dat", "r");
fscanf(f,"%lf", &a[i]);
printf ("%lf", &a[i]);
}
在c中以讀取模式使用FILE時,您必須了解三件事。 1)首先通過fopen()打開文件; 2)檢查文件是否打開。 3)通過fclose()關閉文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.