Chào các bạn! Truyen4U chính thức đã quay trở lại rồi đây!^^. Mong các bạn tiếp tục ủng hộ truy cập tên miền Truyen4U.Com này nhé! Mãi yêu... ♥

bai tap ve file

#include<stdio.h>

#include<time.h>

void sinhngaunhien(char * tenfile, int n, int maxval);

void docfile(char * tenfile);

void songuyento(char * file1, char * file2);

int ktnguyento(int n);

int main()

{

int n;

int maxval = 1000;

char file1[] ="dat1.txt";

char file2[13] ="nt.txt";

printf("Nhap n=");

scanf("%d",&n);

sinhngaunhien(file1,n,maxval);

printf("File ngau nhien:

");

docfile(file1);

songuyento(file1,file2);

printf("

File chua cac so nguyen to:

");

docfile(file2);

system("pause");

return 0;

}

int ktnguyento(int n)

{

int i;

int m;

if (n==1)

return 0;

m = (int)sqrt(n);

for(i=2;i<=m;i++)

if(n % i == 0)

return 0;

return 1;

}

void sinhngaunhien(char * tenfile, int n, int maxval)

{

// sinh ngau nhien n so nguyen nho hon maxval

// ghi n so nguyen vao file co ten la tenfile

int i, x;

FILE * f;

f = fopen(tenfile,"wt");

if(f==NULL)

{

printf("Loi mo file %s", tenfile);

return;

}

srand(time(NULL));

fprintf(f,"%d ", n);

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

{

x = rand() % maxval;

fprintf(f, "%d ", x);

}

fclose(f);

}

void songuyento(char * file1, char * file2)

{

int n, m, i;

int x[10000];

FILE * f1, *f2;

f1 = fopen(file1,"rt");

f2 = fopen(file2,"wt");

if(f1==NULL||f2==NULL)

{

printf("Loi mo file");

return;

}

fscanf(f1,"%d", &n);

m = 0;

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

{

fscanf(f1,"%d", &x[m]);

if(ktnguyento(x[m])==1)

m++;

}

fprintf(f2, "%d ", m);

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

fprintf(f2, "%d ", x[i]);

fclose(f1);

fclose(f2);

}

void docfile(char * tenfile)

{

int i, n;

int x;

FILE * f = fopen(tenfile, "rt");

if(f==NULL)

{

printf("Loi mo file %s", tenfile);

return;

}

fscanf(f,"%d", &n); // doc so phan tu

// doc tung phan tu

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

{

fscanf(f,"%d", &x);

printf("%d ", x);

}

fclose(f);

}

Bạn đang đọc truyện trên: Truyen4U.Com