czwartek, 6 kwietnia 2023

sendfile, malloc, free() - example C

 #include <stdio.h>

#include <stdlib.h>

#include <math.h>

#include <fcntl.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/sendfile.h>


#define kk 10

#define mm kk*kk


int** tab;

double** tab_Sqrt;

double** tab_Aver;


struct stat new_Buff;


struct Point

{

int m_Int;

double m_Sqrt;

double m_Aver;

};


 int date_File,copy_date_File;

int main(int argc, char **argv)

{

int i,j,k,l;

FILE *fp;

off_t off1;

tab=malloc(kk*sizeof(int*));

tab_Sqrt=malloc(kk*sizeof(double*));

tab_Aver=malloc(kk*sizeof(double*));

off1=0;

struct Point* new_Point=malloc(mm*(sizeof(struct Point)));

for(i=0;i<kk;i++)

{

tab[i]=malloc(kk*sizeof(int));

tab_Sqrt[i]=malloc(kk*sizeof(double));

tab_Aver[i]=malloc(kk*sizeof(double));

}

l=0;

for(i=0;i<kk;i++)

{

for(j=0;j<kk;j++)

{

k=(i+1)*(j+1);

tab[i][j]=k;

tab_Sqrt[i][j]=sqrt(1.00*k);

tab_Aver[i][j]=1.00/(1.00*k);

new_Point[l].m_Int=tab[i][j];

new_Point[l].m_Sqrt=tab_Sqrt[i][j];

new_Point[l].m_Aver=tab_Aver[i][j];

++l;

}

}

if ((fp=fopen("new_Point.txt", "w"))==NULL) 

{

     printf ("Can't open the file - new_Point.txt\n");

     exit(1);

     }

     for(i=0;i<mm;i++)

     {

fprintf(fp,"%d",new_Point[i].m_Int);

fprintf(fp,"%.2f",new_Point[i].m_Sqrt);

fprintf(fp,"%.2f",new_Point[i].m_Aver);

fprintf(fp,"\n");

}

fclose(fp);

date_File=open("new_Point.txt",O_RDONLY);

fstat(date_File,&new_Buff);

copy_date_File=open("copy_Point.txt",O_WRONLY | O_CREAT,new_Buff.st_mode);

sendfile(copy_date_File,date_File,off1,new_Buff.st_size);

close(copy_date_File);

close(date_File);

for(i=0;i<kk;i++)

{

free(tab[i]);

free(tab_Sqrt[i]);

free(tab_Aver[i]);

}

free(new_Point);

free(tab_Aver);

free(tab_Sqrt);

free(tab);

return 0;

}


Brak komentarzy:

Prześlij komentarz