C/C++ tilida fayllar bilan ishlash uchun # include ulanishi kerak. ( faylli oqim) # include ning funksiyalari mavjud bo’lib, ularning vazifalari quyidagicha: 1. ofstream - ma’lumotli fayl hosil qilish 2. ifstream – ma’lumotli fayldan foydalanish Ularning yozilishi quyidagicha: ofstream name (“path & file_name”); ifstream name (“path & file_name”); Masalan: ofstream farruh ( “c:\bc \ bin \ fara.dat”); yoki ofstream shoh (“jahon .dat”); ofstream zara ( “nara.txt”); Bu erda: farruh, shoh, zara → oqim nomi fara, jahon, nara → fayl nomi (fayllar .dat va .txt kengaytmali bo’lishi mumkin) Endi bu hosil qilingan fayllardan foydalanish quyidagicha bo’ladi: ifstream farruh ( “c:\bc \ bin \ fara.dat”); yoki ifstream shoh ( “jahon.dat”); ifstream zara ( “nara .txt”); Ochilgan fayllarni albatta yopish shart! name.close( ); Masalan: fattuh.close( ); shoh. close ( ); zara. close ( ); 1-misol. 2ta butun son va ularning yig’indisini o’zida saqlovchi fayl hosil qiling. Undan keyingi dasturda foydalaning. Sonlar →a,b ; Yig’indi → s; Fayl nomi →toha; Oqim nomi → jasur; # include # include # include void main ( ) { int a = 12, b = 13, s; ofstream jasur (“ toha.dat “ ); s = a + b; сout << ” s = ” << s << endl; jasur << s << endl; jasur . close ( ); getch ( ); } Endi bu fayldan foydalanamiz: # include < iostream.h > # include < fstream.h > # include < conio.h > # include < math.h > void main ( ) { int s; float s1; ifstream jasur (“ toha . dat “ ); jasur >> s; s1 = sin (s); cout << “ s1 = “ << s1 << endl; jasur . close ( ); getch( ); } Matrisa va vectorlar berilgan. Son qiymatlari tasodifiy. Ushbu qiymatlardan foydalanib matrisani vectorga ko’paytirish, berilgan matrisanining izini hisoblash, vectorning yig’indisini hisoblash dasturini tuzing. Matrisa va vecrorlarning tasodifiy qiymatlarini hosil qilish va ularni saqlash uchun fayl yarating. Fayl nomi → akbar Oqim nomi → said # include < fstream.h > # include < stdlib.h > # include < time.h > void main ( ) { srand (time (0)); int a [10][10], b[10], i, j; ofstream said ("akbar.txt"); for ( i=0; i<10; i++) { for (j=0; j<10; j++) { a[i][j] = rand( ); said << a[i][j]; } } for (i=0; i<10; i++) { b[i] = rand( ); said << b[i]; } said . close ( ); } Endi bu fayldan foydalanamiz: # include # include void main ( ) { int a[10][3], b[10], i, j, c[10], s1=0, s2=0; ifstream said (“ akbar . txt “ ); for ( i=0; i<10; i++) for (j=0; j<10; j++) said >> a[i][j]; for ( i=0; i<10; i++) said >> b[i]; // davomi for ( i=0; i<3; i++) { c[i] = 0; for (j=0; j<3; j++) c[i] = c[i] + a[i][j] * b[i]; // ko’paytma cout << "c=“ << c[i] << endl; } for ( i=0; i<3; i++) s1 = s1 + a[i][i]; // matrisaning izi for ( i=0; i<3; i++) s2=s2 + b[i]; // vectorning yig’indisi cout << "s1="<Download 62,4 Kb. Do'stlaringiz bilan baham: |