W
Hallo,
die Funktion getDatafromFile liest mittlerweile ganz erfolgreich ein Datenfeld aus einer Datei ein. Aber das Programm stürtzt trotzdem immer ab. Ich sehe den Fehler nicht...vielleicht hat jemand eine Idee.
(P.S.: Das Programm läuft, wenn der Speicher bei Programmende nicht wieder freigegeben wird. free(matrix); im HP)
Danke.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
void write2File(FILE *fPtr, double *matrix, int imax, int jmax) {
int i, j;
for (i=0; i<imax; i++) {
for (j=0; j<jmax; j++) {
fprintf(fPtr, "%4lf\t", matrix[i*imax+j]);
}
fprintf(fPtr,"\n");
}
}
void getDatafromFile(FILE *fPtr, double *matrix, const int imax, const int jmax) {
char buffer[512];
char fChar;
int ckey;
int QUIT;
int i;
int j=0;
do {
i = 0;
// Inhalt von buffer löschen
strcpy(buffer, "");
// Einlesen von Einzelzeichen bis ein Leerzeichen, Zeilenumbruch oder Zeilenende erreicht wird.
QUIT = FALSE;
do {
fChar = fgetc(fPtr);
ckey = (int) fChar;
if ((ckey == 9) || (ckey == 10)) {
QUIT = TRUE;
} else {
buffer[i] = fChar;
buffer[i+1] = '\0';
i++;
}
} while ((QUIT != TRUE) && (!feof(fPtr)));
if (strcmp(buffer,"") == 1) {
matrix[j] = atof(buffer);
j++;
}
} while ((!feof(fPtr)) || (j < imax*jmax));
// Auffüllen der verbleibenden Elemente
if (j < imax*jmax) {
for (j=j; j<imax*jmax; j++) {
matrix[j] = 0;
}
}
}
void main(void) {
int ij;
int i, j;
int imax, jmax;
FILE *fPtr1, *fPtr2;
printf("> Anzahl der Zeilen des Datenfeldes: ");
scanf("%d", &imax);
printf("> Anzahl der Spalten des Datenfeldes: ");
scanf("%d", &jmax);
double *matrix = (double*) malloc(sizeof(double)*imax*jmax);
printf("--------------------------------------------------\n");
printf("> Bitte geben Sie das Datenfeld ein....\n");
printf("--------------------------------------------------\n");
for (i=0; i<imax; i++) {
for (j=0; j<jmax; j++) {
printf("> Element [%d][%d]: ", i+1, j+1);
scanf("%lf", &matrix[i*imax+j]);
}
}
printf("--------------------------------------------------\n");
// SCHREIBE IN DATEI
fPtr1 = fopen("ausgabe.dat", "w");
if (fPtr1 != NULL) {
write2File(fPtr1, matrix, imax, jmax);
fclose(fPtr1);
} else {
printf("> ERROR: Konnte die Datei nicht zum Schreiben oeffnen...\n");
}
// LESE AUS DATEI
printf("--------------------------------------------------\n");
printf("Einlesen aus einer Datei.\n");
printf("--------------------------------------------------\n");
fPtr2 = fopen("ausgabe.dat", "r");
if (fPtr1 != NULL) {
getDatafromFile(fPtr2, matrix, imax, jmax);
fclose(fPtr2);
for (i=0; i<imax; i++) {
for (j=0; j<jmax; j++) {
ij = i*jmax + j;
printf("> A[%d]=%.3lf\n", ij, matrix[ij]);
}
}
} else {
printf("> ERROR: Konnte die Datei nicht zum Lesen oeffnen...\n");
}
free(matrix);
}