🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Structs and files: writing a sensor log to CSV

Group related data into a single type with struct and typedef, access it through a pointer with ->; write sensor readings to a CSV file and read them back with fopen, fprintf and fscanf.

A sensor reading is more than a single number: when it was taken, the temperature, the supply voltage… If you keep these in three separate arrays, the data gets mixed up the moment you sort one array and forget the others. A struct bundles related fields of different types into one package. And once you can write those packages to a file, you don't lose your data even when the program closes. In this lesson we'll combine the two and write a simple data logger.

struct: define your own data type

#include <stdio.h>

struct Olcum {
    int zaman_s;
    double sicaklik_c;
    double gerilim_v;
};

int main(void) {
    struct Olcum o1 = {0, 24.5, 3.30};
    struct Olcum o2 = {.zaman_s = 10, .gerilim_v = 3.28, .sicaklik_c = 24.9};

    printf("t=%d s, T=%.1f C, V=%.2f V\n", o1.zaman_s, o1.sicaklik_c, o1.gerilim_v);
    o2.sicaklik_c += 0.3;
    printf("t=%d s, T=%.1f C, V=%.2f V\n", o2.zaman_s, o2.sicaklik_c, o2.gerilim_v);
    printf("Boyut: %zu bayt\n", sizeof(struct Olcum));
    return 0;
}
t=0 s, T=24.5 C, V=3.30 V
t=10 s, T=25.2 C, V=3.28 V
Boyut: 24 bayt
  • Fields are accessed with the dot operator: o1.sicaklik_c.
  • The .field = value form used for o2 is called a designated initializer (C99). The order doesn't matter and the code explains itself.
  • The fields add up to 4 + 8 + 8 = 20 bytes, yet sizeof gave 24. The compiler added 4 bytes of padding after the int so the doubles sit at addresses that are multiples of 8. This value can differ between platforms; the detail becomes important when you send a struct as raw bytes to hardware or over a network.

typedef, arrays of structs and the -> operator

Instead of writing struct Olcum every time, you can give the type a short name with typedef. Below we calculate the daily energy use of the appliances in a home:

#include <stdio.h>

typedef struct {
    char ad[12];
    double guc_w;
    double sure_saat;
} Cihaz;

double enerji_kwh(const Cihaz *c) {
    return c->guc_w * c->sure_saat / 1000.0;
}

int main(void) {
    Cihaz liste[3] = {
        {"Klima", 1500.0, 6.0},
        {"Buzdolabi", 150.0, 24.0},
        {"Aydinlatma", 60.0, 5.0}
    };
    double toplam = 0.0;

    for (int i = 0; i < 3; i++) {
        double e = enerji_kwh(&liste[i]);
        printf("%-11s %6.2f kWh\n", liste[i].ad, e);
        toplam += e;
    }
    printf("Gunluk toplam: %.2f kWh\n", toplam);
    return 0;
}
Klima         9.00 kWh
Buzdolabi     3.60 kWh
Aydinlatma    0.30 kWh
Gunluk toplam: 12.90 kWh

We gave the function the struct's address, not a copy; for large structs this is both faster and saves memory. To reach a field through a pointer you write c->guc_w, a shorthand for (*c).guc_w. The rule is simple: if you have a struct, use a dot; if you have a pointer to a struct, use an arrow.

Writing to a file: fopen, fprintf, fclose

#include <stdio.h>

typedef struct {
    int zaman_s;
    double sicaklik_c;
    double gerilim_v;
} Olcum;

int main(void) {
    Olcum veri[4] = {
        {0, 24.5, 3.30}, {10, 24.9, 3.29}, {20, 25.6, 3.27}, {30, 26.2, 3.26}
    };

    FILE *fp = fopen("sensor_kayit.csv", "w");
    if (fp == NULL) {
        printf("Dosya acilamadi!\n");
        return 1;
    }
    fprintf(fp, "zaman_s,sicaklik_c,gerilim_v\n");
    for (int i = 0; i < 4; i++) {
        fprintf(fp, "%d,%.1f,%.2f\n", veri[i].zaman_s, veri[i].sicaklik_c, veri[i].gerilim_v);
    }
    fclose(fp);
    printf("4 kayit yazildi.\n");
    return 0;
}
4 kayit yazildi.

Contents of the sensor_kayit.csv file created in the program folder:

zaman_s,sicaklik_c,gerilim_v
0,24.5,3.30
10,24.9,3.29
20,25.6,3.27
30,26.2,3.26
ModeMeaning
"r"Open for reading; returns NULL if the file doesn't exist.
"w"Open for writing; if the file exists its contents are erased, otherwise it is created.
"a"Open for appending; old records are kept.

fprintf is the version of printf that writes to a file; its first argument is the file pointer. fclose writes the buffered data to disk and closes the file.

Excel set to a Turkish (or other European) locale expects a semicolon as the CSV separator and a comma as the decimal mark; when you double-click the file, everything may land in a single column. Importing it through Data > From Text/CSV and choosing comma as the separator and dot as the decimal mark solves the problem.

Reading from a file: fgets and fscanf

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("sensor_kayit.csv", "r");
    if (fp == NULL) {
        printf("Dosya acilamadi!\n");
        return 1;
    }

    char baslik[64];
    if (fgets(baslik, sizeof(baslik), fp) == NULL) {   // ilk satiri atla
        fclose(fp);
        return 1;
    }

    int t, adet = 0;
    double sic, ger, toplam = 0.0, enb = -1000.0;
    while (fscanf(fp, "%d,%lf,%lf", &t, &sic, &ger) == 3) {
        toplam += sic;
        if (sic > enb) enb = sic;
        adet++;
    }
    fclose(fp);

    printf("Kayit sayisi : %d\n", adet);
    printf("Ort. sicaklik: %.2f C\n", toplam / adet);
    printf("En yuksek    : %.1f C\n", enb);
    return 0;
}
Kayit sayisi : 4
Ort. sicaklik: 25.30 C
En yuksek    : 26.2 C

fgets reads one line (at most the size of the array); here we used it to skip the header line. fscanf is the version of scanf that reads from a file and follows the same rule: it returns the number of fields read successfully. When the file ends or the format breaks, it returns something other than 3 and the loop stops.

Common mistakes

Wiping an existing log with "w": the old readings disappear every time you open it. For continuous logging, use "a".

  • Not checking the result of fopen: if the folder doesn't exist, the file is locked by another program or you lack permission, fopen returns NULL; calling fprintf with NULL leads to a crash.
  • Forgetting fclose: the last lines waiting in the buffer may never reach the disk.
  • Using a dot with a pointer: not c.guc_w but c->guc_w.

Exercise

Write the function void kaydet(FILE *fp, const Olcum *o): it should write one reading to the file as a CSV line. Then open sensor_kayit.csv in append mode and add a reading taken at second 40: 26.8 °C, 3.25 V.

Hint: inside the function use fprintf(fp, "%d,%.1f,%.2f\n", o->zaman_s, ...). In main, open the file with fopen(..., "a") and pass &yeni to the function.

Solution

#include <stdio.h>

typedef struct {
    int zaman_s;
    double sicaklik_c;
    double gerilim_v;
} Olcum;

void kaydet(FILE *fp, const Olcum *o) {
    fprintf(fp, "%d,%.1f,%.2f\n", o->zaman_s, o->sicaklik_c, o->gerilim_v);
}

int main(void) {
    Olcum yeni = {40, 26.8, 3.25};

    FILE *fp = fopen("sensor_kayit.csv", "a");
    if (fp == NULL) {
        printf("Dosya acilamadi!\n");
        return 1;
    }
    kaydet(fp, &yeni);
    fclose(fp);
    printf("Kayit eklendi.\n");
    return 0;
}
Kayit eklendi.

The final state of the file:

zaman_s,sicaklik_c,gerilim_v
0,24.5,3.30
10,24.9,3.29
20,25.6,3.27
30,26.2,3.26
40,26.8,3.25

You've packaged data with struct and written it permanently to a file and read it back. In the final lesson we'll carry all of this over to a microcontroller and learn to manage registers with bit masks and the volatile keyword.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. If Cihaz *c is a pointer to a struct, what is the correct way to access the guc_w field?
2. What happens if an existing file is opened with fopen(name, "w")?
3. When does the loop while (fscanf(fp, "%d,%lf", &t, &v) == 2) stop?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.