Dasturlash” fanidan tayyorlagan


int bayt = ftell(f); cout


Download 17.22 Kb.
bet3/3
Sana22.10.2023
Hajmi17.22 Kb.
#1716195
1   2   3
Bog'liq
das. mus. 4

int bayt = ftell(f);
cout << k <<" ftell(f)=" << bayt << endl;
}
fclose(f);
system (“pause”);
return 0;
}

Misol 3. n natural soni berilgan. Elementlari n ta butun sondan iborat bo`lgan faylni hosil qiluvchi va juft elementlar ini 2 marta orttiruvchi programma tuzilsin.
#include
#include
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(k), 1, f);
if (k % 2 == 0 )
{
k *= 2;
// fayl ko'rsatkichini sizeof(int)
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 elementlari\n";
rewind(f);
while (fread(&k, sizeof(k), 1, f))
cout << k << 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 o'rnini eslab qolish
int pos = ftell(f);
fread(&k, sizeof(k), 1, f);
if (k % 2 == 0 )
{
k *= 2;
// fayl ko'rsatkichini oldingi xolatiga o'rnatish
fseek(f, pos, SEEK_SET);
fwrite(&k, sizeof(int), 1, f);
// fayl ko'rsatkichi o'rnini 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 << k << endl;
fclose(f);
system (“pause”);
return 0;
}

Download 17.22 Kb.

Do'stlaringiz bilan baham:
1   2   3




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling