Skip to content

10-dars: File I/O (Fayl bilan ishlash)

Dars haqida

Davomiyligi: 90 daqiqa Maqsad: Talaba fayl ochish, yozish, o'qish va yopishni o'rganishi kerak.

1. Nima uchun fayl?

Dastur tugagandan keyin — xotirada saqlangan ma'lumot yo'qoladi.

Fayl — ma'lumotni diskda saqlash.

2. FILE pointer

c
#include <stdio.h>

FILE *fp;  // fayl pointeri

FILE — standart struct, fayl haqida ma'lumot saqlaydi.

3. fopen — fayl ochish

c
FILE *fp = fopen("data.txt", "r");

Rejimlar:

ModeVazifa
"r"Read (o'qish)
"w"Write (yozish, mavjud bo'lsa o'chiriladi)
"a"Append (qo'shish)
"r+"Read + Write
"w+"Write + Read (ustiga yozish)
"a+"Append + Read
"rb"Binary read
"wb"Binary write

4. NULL tekshirish

c
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    printf("Faylni ochib bo'lmadi!\n");
    return 1;
}

Doim tekshiring — fayl yo'q, ruxsat yo'q yoki boshqa muammo bo'lishi mumkin.

5. fclose — fayl yopish

c
fclose(fp);

Doim yoping — ma'lumot diskka yoziladi va resurs bo'shatiladi.

6. fprintf — faylga yozish

printf'ga o'xshash, lekin faylga:

c
FILE *fp = fopen("output.txt", "w");
if (!fp) return 1;

fprintf(fp, "Salom dunyo!\n");
fprintf(fp, "Yoshim: %d\n", 22);
fprintf(fp, "Pi: %.5f\n", 3.14159);

fclose(fp);

Fayl ichida:

Salom dunyo!
Yoshim: 22
Pi: 3.14159

7. fscanf — fayldan o'qish

scanf'ga o'xshash:

c
FILE *fp = fopen("data.txt", "r");
if (!fp) return 1;

int n;
double d;
char s[100];

fscanf(fp, "%d %lf %s", &n, &d, s);
printf("%d %f %s\n", n, d, s);

fclose(fp);

8. fgetc va fputc — bitta belgi

c
FILE *fp = fopen("data.txt", "r");
int c;

while ((c = fgetc(fp)) != EOF) {
    putchar(c);
}

fclose(fp);

fgetc — bitta belgi. EOF — End Of File.

9. fgets va fputs — qator

c
FILE *fp = fopen("data.txt", "r");
char line[256];

while (fgets(line, sizeof(line), fp) != NULL) {
    printf("%s", line);  // line'da \n bor
}

fclose(fp);
c
FILE *fp = fopen("output.txt", "w");
fputs("Birinchi qator\n", fp);
fputs("Ikkinchi qator\n", fp);
fclose(fp);

10. Misol: Yozish va o'qish

Yozish:

c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("students.txt", "w");
    if (!fp) return 1;
    
    fprintf(fp, "Akmal 22 95.5\n");
    fprintf(fp, "Aziza 19 92.0\n");
    fprintf(fp, "Botir 25 78.5\n");
    
    fclose(fp);
    printf("Yozildi!\n");
    return 0;
}

O'qish:

c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("students.txt", "r");
    if (!fp) return 1;
    
    char name[50];
    int age;
    double score;
    
    while (fscanf(fp, "%s %d %lf", name, &age, &score) == 3) {
        printf("%s, %d yosh, %.1f ball\n", name, age, score);
    }
    
    fclose(fp);
    return 0;
}

11. Append rejim

c
FILE *fp = fopen("log.txt", "a");
fprintf(fp, "Yangi log: %s\n", "ish boshlandi");
fclose(fp);

Mavjud fayl o'chirilmaydi — yangi ma'lumot oxiriga qo'shiladi.

12. Binary file

Matn emas, bayt-bayt yozish/o'qish.

c
#include <stdio.h>

typedef struct {
    char name[50];
    int age;
    double score;
} Student;

int main(void) {
    Student students[3] = {
        {"Akmal", 22, 95.5},
        {"Aziza", 19, 92.0},
        {"Botir", 25, 78.5}
    };
    
    // Yozish (binary)
    FILE *fp = fopen("students.bin", "wb");
    fwrite(students, sizeof(Student), 3, fp);
    fclose(fp);
    
    // O'qish (binary)
    Student loaded[3];
    fp = fopen("students.bin", "rb");
    fread(loaded, sizeof(Student), 3, fp);
    fclose(fp);
    
    for (int i = 0; i < 3; i++) {
        printf("%s %d %.1f\n", loaded[i].name, loaded[i].age, loaded[i].score);
    }
    
    return 0;
}

13. fread va fwrite

c
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
  • ptr — qaysi joydan/joyga
  • size — bir elementning hajmi
  • count — necha element
  • Return: muvaffaqiyatli o'qilgan/yozilgan element soni

14. fseek va ftell

Fayl ichida harakat:

c
fseek(fp, 100, SEEK_SET);  // boshidan 100 byte
fseek(fp, -10, SEEK_END);  // oxirdan -10 byte
fseek(fp, 50, SEEK_CUR);   // hozirgi joydan +50

long position = ftell(fp);  // hozirgi joy
KonstantaMa'no
SEEK_SETBoshidan
SEEK_CURHozirgi joydan
SEEK_ENDOxirdan

15. Fayl hajmini topish

c
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);  // boshiga qaytish

printf("Fayl hajmi: %ld byte\n", size);

16. Misol: Word count

c
#include <stdio.h>
#include <ctype.h>

int main(void) {
    FILE *fp = fopen("document.txt", "r");
    if (!fp) return 1;
    
    int chars = 0, words = 0, lines = 0;
    int in_word = 0;
    int c;
    
    while ((c = fgetc(fp)) != EOF) {
        chars++;
        
        if (c == '\n') lines++;
        
        if (isspace(c)) {
            in_word = 0;
        } else if (!in_word) {
            in_word = 1;
            words++;
        }
    }
    
    fclose(fp);
    
    printf("Belgilar: %d\n", chars);
    printf("So'zlar: %d\n", words);
    printf("Qatorlar: %d\n", lines);
    
    return 0;
}

Unix'dagi wc buyrug'iga o'xshash.

17. Misol: Cat dasturi

c
#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Foydalanish: %s <fayl>\n", argv[0]);
        return 1;
    }
    
    FILE *fp = fopen(argv[1], "r");
    if (!fp) {
        printf("Faylni ochib bo'lmadi: %s\n", argv[1]);
        return 1;
    }
    
    int c;
    while ((c = fgetc(fp)) != EOF) {
        putchar(c);
    }
    
    fclose(fp);
    return 0;
}

Kompilyatsiya: gcc cat.c -o mycat Ishlatish: ./mycat hello.txt

18. Misol: Faylni nusxalash

c
#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Foydalanish: %s <src> <dst>\n", argv[0]);
        return 1;
    }
    
    FILE *src = fopen(argv[1], "rb");
    FILE *dst = fopen(argv[2], "wb");
    
    if (!src || !dst) return 1;
    
    char buffer[1024];
    size_t n;
    while ((n = fread(buffer, 1, sizeof(buffer), src)) > 0) {
        fwrite(buffer, 1, n, dst);
    }
    
    fclose(src);
    fclose(dst);
    
    printf("Nusxalandi: %s -> %s\n", argv[1], argv[2]);
    return 0;
}

19. Common pitfalls

1. NULL tekshirmaslik

c
FILE *fp = fopen("yoq.txt", "r");
fprintf(fp, "...");  // CRASH (fp = NULL)

2. fclose unutish

c
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "...");
// fclose yo'q — ma'lumot diskka yozilmasligi mumkin

3. Buffer kichik

c
char line[10];
fgets(line, sizeof(line), fp);
// uzun qator kesiladi

4. Mode noto'g'ri

c
fopen("file.txt", "w");
fread(...);  // XATO — write mode

fopen("file.txt", "r");
fwrite(...);  // XATO

20. Standart fayllar

3 ta avtomatik fayl:

  • stdin — klaviatura
  • stdout — ekran
  • stderr — xato chiqarish
c
fprintf(stderr, "Xato: %s\n", message);  // ekranga (xato uchun)
fprintf(stdout, "OK\n");                  // ekranga
fscanf(stdin, "%d", &n);                  // klaviaturadan

scanf aslida fscanf(stdin, ...) ga teng.

Darsdagi topshiriqlar

1 — Birinchi fayl

first.c:

c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("hello.txt", "w");
    if (!fp) return 1;
    
    fprintf(fp, "Salom dunyo!\n");
    fprintf(fp, "Bu mening birinchi faylim.\n");
    
    fclose(fp);
    printf("Yozildi!\n");
    return 0;
}

cat hello.txt qiling — nima ko'rinadi?

2 — O'qish

read-file.c:

c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("hello.txt", "r");
    if (!fp) return 1;
    
    char line[256];
    while (fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);
    }
    
    fclose(fp);
    return 0;
}

3 — Talabalar fayli

students-io.c:

  1. 5 ta talaba ma'lumotini students.txt'ga yoz
  2. Faylni o'qib chiqar
  3. O'rtacha ballni hisoblash

4 — Append log

log.c:

c
#include <stdio.h>
#include <time.h>

int main(void) {
    FILE *fp = fopen("app.log", "a");
    if (!fp) return 1;
    
    time_t now = time(NULL);
    fprintf(fp, "[%ld] Dastur ishga tushdi\n", now);
    
    fclose(fp);
    return 0;
}

Dasturni 5 marta ishga tushirib, log faylni ko'ring.

5 — Word count

wc.c — Dars matnidagi to'liq dastur.

Sinab ko'ring: turli .txt fayllar bilan.

6 — Cat

mycat.c — fayl tarkibini ekranga.

Argument bilan:

bash
./mycat hello.txt

7 — Copy

mycopy.c — fayl nusxalash.

bash
./mycopy src.txt dst.txt

8 — Binary struct

binary.c:

Talabalar struct massivini binary faylga yozing va o'qing.

Hajmni taqqoslang: matnli vs binary versiya.

9 — Phone book

phonebook.c:

c
typedef struct {
    char name[50];
    char phone[20];
} Contact;
  • Faylga yozish
  • Faylga qo'shish (append)
  • Faylni o'qib chiqarish
  • Ism bo'yicha qidirish

10 — GitHub

bash
$ mkdir 5-oy-dars-10
$ git add . && git commit -m "feat: dars 10 - file I/O" && git push

Lug'at

TerminIzoh
FILEFayl pointeri
fopenFayl ochish
fcloseFayl yopish
fprintfFaylga yozish (formatlangan)
fscanfFayldan o'qish (formatlangan)
fgets / fputsQator
fgetc / fputcBelgi
fread / fwriteBinary o'qish/yozish
fseek / ftellFayl ichida harakat
EOFEnd Of File
stdin / stdout / stderrStandart fayllar
Binary fileBayt-bayt fayl
Text fileMatn fayl

Keyingi dars

11-dars: Mini loyiha →

Master IT o'quv markazi — o'qitish rejasi