pagratios Δημοσ. 19 Ιουλίου 2011 Δημοσ. 19 Ιουλίου 2011 Θέλω να έχω έναν πίνακα FILE για να ανοίγω τα αρχεία με χρήση for καθώς και τα ονόματα τους είναι με την χρήση αριθμών πχ file_0,file_1... Όμως τις μεταβλητές FILE τις δηλώνεις FILE *pf οπότε για πίνακα πρέπει FILE **pf αλλά πως θα γίνει το malloc σε αυτή την περίπτωση?
migf1 Δημοσ. 19 Ιουλίου 2011 Δημοσ. 19 Ιουλίου 2011 > /* * ΤΡΟΠΟΣ 1 */ #include <stdio.h> #include <stdlib.h> #define MAXFNAME 255+1 #define FNAME_PREFIX "file_" // ------------------------------------------------------------------------------------ int main( void ) { const int maxfiles = 4; FILE **farray; char fname[ MAXFNAME ] = ""; register int i; farray = calloc(maxfiles, sizeof(FILE *) ); if ( !farray ) { puts("*** error: out of memory"); exit(1); } for (i=0; i < maxfiles; i++) { sprintf(fname, "%s%d.txt", FNAME_PREFIX, i); farray[i] = fopen(fname, "a"); if ( !farray[i] ) printf("*** error: failed to create file: %s\n", fname); fprintf(farray[i], "%d\n", i); } for (i=0; i < maxfiles; i++) { if ( farray[i] ) fclose( farray[i] ); } free( farray ); exit(0); } > /* * ΤΡΟΠΟΣ 2 */ #include <stdio.h> #include <stdlib.h> #define MAXFNAME 255+1 #define FNAME_PREFIX "file_" typedef struct fslot { FILE *fp; }FSlot; // ------------------------------------------------------------------------------------ int main( void ) { const int maxfiles = 4; FSlot *farray; char fname[ MAXFNAME ] = ""; register int i; farray = calloc( maxfiles, sizeof(FSlot) ); if ( !farray ) { puts("*** error: out of memory"); exit(1); } for (i=0; i < maxfiles; i++) { sprintf(fname, "%s%d.txt", FNAME_PREFIX, i); farray[i].fp = fopen(fname, "a"); if ( !farray[i].fp ) printf("*** error: failed to create file: %s\n", fname); fprintf(farray[i].fp, "%d\n", i); } for (i=0; i < maxfiles; i++) { if ( farray[i].fp ) fclose( farray[i].fp ); } free( farray ); exit(0); }
Προτεινόμενες αναρτήσεις
Αρχειοθετημένο
Αυτό το θέμα έχει αρχειοθετηθεί και είναι κλειστό για περαιτέρω απαντήσεις.