works:programmer:cpp:read-write-file

Программа пример чтения/записи файла на C++

#include <iostream>
#include <list>
#include <fstream>
 
using namespace std;
 
typedef struct {
    string author;
    string book;
    unsigned short published;
    float price;
    string category;
} Bookshelf;
 
list<Bookshelf> bookshelf;
 
void add(string author, string book, unsigned short published, float price, string category) {
    Bookshelf item = *(new Bookshelf());
    item.author = author;
    item.book = book;
    item.published = published;
    item.price = price;
    item.category = category;
    bookshelf.push_back(item);
}
 
void freemem(void) {
    bookshelf.clear();
}
 
int main(void) {
 
    add("Vasilij Pupkin", "Kniga", 1990, 20, "Hlam");
    add("Tester", "testie", 1991, 10.5, "Hlam");
    // write out
    ofstream out("output.txt");
    for (auto book: bookshelf) {
        out << book.author << endl << book.book << endl
            << book.published << endl << book.price << endl
            << book.category << endl;
    }
    freemem();
    out.flush();
    out.close();
    // read in
    string author, book, published, price, category;
    ifstream in("output.txt");
    while (!in.eof()) {
        if (getline(in, author) && getline(in, book) &&
            getline(in, published) && getline(in, price) &&
            getline(in, category))
        {
            add(author, book, stoi(published), stof(price), category);
        }
    }
    in.close();
    // list
    for (auto book: bookshelf) {
        cout << "Author: " << book.author << endl
            << "Book: " << book.book << endl
            << "Published: " << book.published << endl
            << "Price: " << book.price << endl
            << "Category: " << book.category << endl << endl;
    }
    freemem();
    return 0;
}
works/programmer/cpp/read-write-file.txt · Last modified: 2021/12/03 12:04 by Chugreev Eugene