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

File handling: writing and reading a sensor CSV with fstream

Write sensor readings to a CSV file with std::ofstream, read them back with std::ifstream, getline and stringstream; skip broken lines with exceptions and summarise the result with lambdas.

The data logger in the mini project worked well, but it had one problem: when the program closed, all the readings were lost. A real logger writes its data to disk so that you can open it the next day, plot it in Excel or hand it to another program. The most common format for this is CSV (Comma-Separated Values): each line is a record, the fields are separated by commas, and the first line holds the column names. Working with files in C++ is very similar to working with the screen, because files are streams too. You write to a file with << just as you write to std::cout. In this final lesson we will combine almost everything you have learned: structs, vectors, exceptions, lambdas and RAII.

Writing to a file: std::ofstream

The <fstream> header provides three classes: std::ofstream for writing, std::ifstream for reading and std::fstream for both. The program below writes five readings to the file olcum.csv. In one of the readings the sensor did not answer; the logger writes ERR on that line instead of a number. This happens a lot on real devices, and the reading program has to be ready for it.

#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>

struct Kayit {
    int dakika;
    double sicaklik;
    bool gecerli;           // sensor cevap verdi mi?
};

int main() {
    std::vector<Kayit> veri = {
        {0, 22.5, true}, {5, 23.0, true}, {10, 0.0, false},
        {15, 24.0, true}, {20, 22.0, true}};

    std::ofstream dosya("olcum.csv");
    if (!dosya) {
        std::cerr << "olcum.csv acilamadi\n";
        return 1;
    }

    dosya << "dakika,sicaklik\n";
    dosya << std::fixed << std::setprecision(1);
    for (const auto& k : veri) {
        dosya << k.dakika << ',';
        if (k.gecerli) {
            dosya << k.sicaklik;
        } else {
            dosya << "ERR";             // sensor zaman asimi
        }
        dosya << '\n';
    }
    std::cout << veri.size() << " satir yazildi\n";
    return 0;
}
5 satir yazildi

The program creates an olcum.csv file with this content in the folder it runs in:

dakika,sicaklik
0,22.5
5,23.0
10,ERR
15,24.0
20,22.0

There are three points to note:

  • Checking that the file opened. Opening fails if the folder does not exist, the file is locked by another program or you have no write permission. if (!dosya) catches this. We wrote the error message to std::cerr; as you saw in the input and output lesson, this stream is separate from normal output.
  • Formatting works the same way. std::fixed and std::setprecision(1) work on a file stream too; that is why the value 23 was written to the file as 23.0.
  • You cannot forget to close it. We did not call close(). The dosya object goes out of scope when main ends, and its destructor flushes the buffer to disk and closes the file. This is exactly the RAII we discussed in the smart pointers lesson.

By default std::ofstream writes the file from scratch; any old data in it is erased. If you want to add new lines to the end of the existing file on every run, use append mode: std::ofstream log("kayit.csv", std::ios::app);.

Reading from a file: getline and stringstream

The most robust way to read is to take the file line by line and then decode each line separately. To split a line into its fields, use std::istringstream from the <sstream> header: it lets you read a string as if it were a file. If you pass ',' as the third argument to std::getline, it reads up to the comma instead of the end of the line.

#include <algorithm>
#include <fstream>
#include <iostream>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

struct Olcum {
    int dakika;
    double sicaklik;
};

// "15,24.0" -> Olcum. Bozuk satirda istisna firlatir.
Olcum satirCoz(const std::string& satir) {
    std::istringstream ss(satir);
    std::string dk, sic;
    if (!std::getline(ss, dk, ',') || !std::getline(ss, sic)) {
        throw std::runtime_error("eksik alan");
    }
    return Olcum{std::stoi(dk), std::stod(sic)};
}

int main() {
    std::ifstream dosya("olcum.csv");
    if (!dosya.is_open()) {
        std::cerr << "olcum.csv bulunamadi\n";
        return 1;
    }

    std::vector<Olcum> veri;
    std::string satir;
    int satirNo = 1;
    std::getline(dosya, satir);                 // baslik satirini atla
    while (std::getline(dosya, satir)) {
        ++satirNo;
        try {
            veri.push_back(satirCoz(satir));
        } catch (const std::exception&) {
            std::cout << "Satir " << satirNo << " atlandi: " << satir << '\n';
        }
    }
    if (veri.empty()) {
        std::cout << "Gecerli olcum yok\n";
        return 1;
    }

    double ort = std::accumulate(veri.begin(), veri.end(), 0.0,
                     [](double t, const Olcum& o) { return t + o.sicaklik; }) / veri.size();
    auto enSicak = std::max_element(veri.begin(), veri.end(),
                     [](const Olcum& a, const Olcum& b) { return a.sicaklik < b.sicaklik; });

    std::cout << veri.size() << " olcum okundu\n";
    std::cout << "Ortalama: " << ort << " C\n";
    std::cout << "En sicak: " << enSicak->sicaklik << " C (dakika " << enSicak->dakika << ")\n";
    return 0;
}
Satir 4 atlandi: 10,ERR
4 olcum okundu
Ortalama: 22.875 C
En sicak: 24 C (dakika 15)

The most important parts of the code:

  • while (std::getline(dosya, satir)): getline returns the stream itself; if the read succeeded, the stream counts as "true", and when the file has ended it counts as "false". The loop runs exactly as many times as there are lines. This is the standard pattern for reading a file.
  • Decoding a line lives in its own function. satirCoz (decode line) does a single job and throws an exception on bad data. When the text "ERR" is given to std::stod, std::invalid_argument is thrown; the catch in the loop catches it, reports the line ("line 4 skipped") and keeps reading. One broken line does not throw away the whole file.
  • A summary with lambdas. The accumulate and max_element patterns from the previous lessons are used here unchanged. The four valid readings add up to 91.5, and their average is 22.875.
  • An empty-data check. If every line in the file had been broken, veri would be empty; we checked this first so that we do not divide by zero or dereference end().

The file the program finds is relative to the working directory, which is not always the folder where the .exe is. IDEs often run the program from the project folder. If you get a "file not found" error, first check which folder the program runs in, or give a full path.

Common mistakes

  • Building the loop with while (!dosya.eof()). eof() becomes true only after a read has hit the end of the file. So the loop runs one extra time and the last line is processed twice, or an empty line is added. Put the read inside the condition: while (std::getline(dosya, satir)).
  • Overwriting instead of appending. A program that opens its log file with std::ofstream log("kayit.csv"); every time erases all earlier records on every run. Appending requires the std::ios::app mode.
  • Forgetting the line-ending difference. If you read a CSV created on Windows on Linux, an invisible '\r' character remains at the end of every line. std::stod tolerates it, but text comparisons such as satir == "ERR" fail. If needed, remove the '\r' at the end of the line.

Exercise

Read the olcum.csv created by the first program and write the readings whose temperature exceeds 22.8 °C to a new file named esik_ustu.csv (above threshold). The new file has three columns: minute, temperature and difference from the threshold. Count the broken lines but do not write them to the file. At the end, print how many lines were written and how many broken lines were skipped. This time, use the >> operator directly instead of getline to decode a line.

Hint: the chain ss >> dakika >> virgul >> sicaklik reads an int, a char (the comma) and a double. If any of the reads fails, the stream goes into the fail state and the expression evaluates to "false". On the line "10,ERR" the number cannot be read, so this check catches the line. You can open two files at the same time: one ifstream and one ofstream.

Solution

#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::ifstream giris("olcum.csv");
    std::ofstream cikis("esik_ustu.csv");
    if (!giris || !cikis) {
        std::cerr << "Dosya acilamadi\n";
        return 1;
    }

    const double esik = 22.8;
    std::string satir;
    std::getline(giris, satir);                 // baslik
    cikis << "dakika,sicaklik,fark\n";
    cikis << std::fixed << std::setprecision(1);

    int yazilan = 0;
    int hatali = 0;
    while (std::getline(giris, satir)) {
        std::istringstream ss(satir);
        int dakika = 0;
        char virgul = 0;
        double sicaklik = 0.0;
        if (!(ss >> dakika >> virgul >> sicaklik) || virgul != ',') {
            ++hatali;
            continue;
        }
        if (sicaklik > esik) {
            cikis << dakika << ',' << sicaklik << ',' << sicaklik - esik << '\n';
            ++yazilan;
        }
    }
    std::cout << yazilan << " satir yazildi, " << hatali << " hatali satir atlandi\n";
    return 0;
}
2 satir yazildi, 1 hatali satir atlandi

The resulting esik_ustu.csv:

dakika,sicaklik,fark
5,23.0,0.2
15,24.0,1.2

You have now seen both ways of decoding: getline + stod is flexible for lines with a varying number of fields or with text, while a >> chain is short for fixed-format numeric lines.

In short, files are streams: you write with ofstream, read with ifstream and getline, and handle broken lines with exceptions; RAII takes care of closing the file. With this lesson you have reached the end of the course. From here you can move on to polymorphism with inheritance and virtual functions, multi-file projects with CMake, and concurrent programming with <thread>. Moving the logger onto an STM32 or ESP32 board is the best way to try what you have learned in the field.

// 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. Which loop is the most correct way to read all the lines of a file?
2. You want to add the new reading to the end of kayit.csv on every run. How should you open the file?
3. What happens if you forget to call close() on a std::ofstream object?

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

// Final exam and certificate

20 random questions from the lessons, 30 minutes, pass mark 70%. If you pass, you get a verifiable certificate of achievement (with a QR code).

Take the final exam

Tip: ← → keys let you move between lessons.