3 - misol. n natural soni berilgan. Elementlari n ta butun sondan iborat bo' Igan faylni hosil qiluvchi va juft elementlarini 2 marta orttiruvchi programma tuzilsin.
#include
#include
using namespace std;
int main() {
int n, k;
FILE *f;
// binar faylni yozish va o'qish uchun ochish
f = fopen("binar", "wb+");
if (f == NULL) {
cout « "Faylni hosil qilishda xato bo'ldi";
return 1; }
cout « "n="; cin » n;
for (int i = 0; i < n; i++) {
cin » k;
fwrite(&k, sizeof(k), 1, f) ; }
// fayl ko'rsatkichini fayl boshiga qo'yish
rewind(f);
while (!feof(f)) // fayl oxiri uchramasa bajar
{
fread(&k, sizeof(к), 1, f);
if (k % 2 == 0 ) {
к *= 2;
// fayl ko'rsatkichini sizeof (int) bayt chapga surish
fseek(f, -sizeof(int), SEEK_CUR);
fwrite(&k, sizeof(int), 1, f);
// fayl ko'rsatkichini o'rnatish
fseek(f, ftell(f), SEEK_SET); } }
cout « "fayl elementlariXn";
rewind(f);
while (fread(&k, sizeof(k), 1, f))
cout « к « endl;
fclose(f);
return 0; }
3 - misolni quyidagicha yechish ham mumkin.
#include
#include
using namespace std;
int main () {
int n, k;
FILE *f;
f = fopen("binar", "wb+");
cout « "n="; cin » n;
for (int i = 0; i < n; i++) {
cin » k;
fwrite(&k, sizeof(k), 1, f) ; }
// fayl ko'rsatkichini fayl boshiga qo'yish
rewind(f);
while (!feof(f)) {
// fayl ko'rsatkichi о'mini eslab qolish
int pos = ftell(f);
fread(&k, sizeof(k), 1, f);
if (k % 2 == 0 ) {
к *= 2;
// fayl ko'rsatkichini oldingi xolatiga o'matish
fseek(f, pos, SEEK_SET);
fwrite(&k, sizeof(int), 1, f) ;
// fayl ko'rsatkichi о'mini sizeof (int) ga surish
pos += sizeof(int);
fseek(f, pos, SEEK_SET); }
}
cout « "fayl elementlari\n";
rewind(f);
// fayl elementlarini chiqarish
while (fread(&k, sizeof(k), 1, f))
cout « к « endl;
fclose(f);
return 0; }
Dostları ilə paylaş: |