C/Tablice - więcej: Różnice pomiędzy wersjami

Dodane 2380 bajtów ,  2 lata temu
m
* fwrite<ref>[http://www.cplusplus.com/reference/cstdio/fwrite/ cplusplus fwrite]</ref>
* fread<ref>[http://www.cplusplus.com/reference/cstdio/fread/ cplusplus fread]</ref>
 
 
<source lang=c>
 
 
#include <stdio.h>
#include <stdlib.h>
 
int main ()
{
FILE * pbFile;
char * fName = "a1.dat";
// input static array
double a[] = { 1.333333333333333 , 1.44444444444444444 , 1.5555555555555555, 1.66666666666666666666666};
long ALength; // number of array's elements = ENumber
size_t ASize; // size of array in bytes
size_t ESize; // size of array's element in bytes
int i;
// for output array (dynamic arrray read from binary file )
double * b; //
size_t result;
size_t FSize;
 
// test input
ASize = sizeof(a); //
ESize = sizeof(a[0]);
ALength = ASize/ESize; // number of elements = Length of array
printf("array has %ld elements of %zu bytes so the array size = %zu bytes\n", ALength, ESize, ASize );
for (i=0; i< ALength; i++)
printf("i = %d \t a[i] = %f\n",i, a[i]);
// write to the binary file
pbFile = fopen (fName, "wb");
fwrite (a , ESize, ALength, pbFile);
fclose (pbFile);
printf("array have been saved to the %s file\n", fName);
// open binary file
pbFile = fopen( fName , "rb" );
if (pbFile==NULL) {fputs ("File open error",stderr); return 1;}
// obtain file size:
fseek (pbFile , 0 , SEEK_END);
FSize = ftell (pbFile);
rewind (pbFile);
printf("file size = %zu\n", FSize);
 
// allocate memory to contain the whole file:
b = (double *) malloc (ESize*ALength);
if (b == NULL) {fputs ("Memory error",stderr); return 2;}
 
// copy the file into the buffer:
result = fread (b,ESize,ALength,pbFile);
if (result != ALength) {printf("Reading error: result = %zu != %ld \n",result, ALength); return 3;}
 
/* the whole file is now loaded in the memory buffer. */
// print the array
printf("array has %ld elements of %zu bytes so the array size = %zu bytes\n", ALength, ESize, ASize );
for (i=0; i< ALength; i++)
printf("i = %d \t b[i] = %f\n",i, b[i]);
// terminate
fclose (pbFile);
free (b);
return 0;
}
 
</source>
 
 
 
Wynik :
 
<source lang=bash>
 
 
gcc a.c -Wall
./a.out
array has 3 elements of 8 bytes so the array size = 24 bytes
i = 0 a[i] = 1.330000
i = 1 a[i] = 1.340000
i = 2 a[i] = 1.350000
array have been saved to the a.dat file
file size = 24
array has 3 elements of 8 bytes so the array size = 24 bytes
i = 0 b[i] = 1.330000
i = 1 b[i] = 1.340000
i = 2 b[i] = 1.350000
 
</source>
 
==Źródła==
6160

edycji