From ce654711db90ee4121f3df12e373f2362f9674ad Mon Sep 17 00:00:00 2001 From: Angel Dimitriev Date: Tue, 15 Mar 2022 19:26:57 +0200 Subject: Add files via upload --- Sem. 03/array_of_students_read.cpp | 56 +++++++++++++++++++++++++++++++++++++ Sem. 03/array_of_students_write.cpp | 38 +++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 Sem. 03/array_of_students_read.cpp create mode 100644 Sem. 03/array_of_students_write.cpp diff --git a/Sem. 03/array_of_students_read.cpp b/Sem. 03/array_of_students_read.cpp new file mode 100644 index 0000000..ab1f425 --- /dev/null +++ b/Sem. 03/array_of_students_read.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +using namespace std; + +struct Student +{ + char name[30]; + int age; + int fn; +}; + +void initStudent(Student& st, const char* name, int age, int fn) +{ + strcpy(st.name, name); + st.age = age; + st.fn = fn; +} + +void saveToFile(const Student* students, size_t count, ofstream& file) +{ + file.write((const char*)students, count * sizeof(Student)); +} + + +size_t getFileSize(ifstream& f) +{ + size_t currentPos = f.tellg(); + f.seekg(0, ios::end); + size_t size = f.tellg(); + + f.seekg(currentPos); + return size; +} + +void readFromFile(Student*& ptr, size_t& studentsCount, ifstream& f) +{ + size_t sizeOfFile = getFileSize(f); + studentsCount = sizeOfFile / sizeof(Student); + ptr = new Student[studentsCount]; + f.read((char*)ptr, sizeOfFile); +} + + +int main() +{ + Student* arr; + size_t count; + ifstream file("students.dat"); + readFromFile(arr, count, file); + + for (int i = 0; i < count; i++) + std::cout << "Name: " << arr[i].name << ", age: " << arr[i].age << ", fn: " << arr[i].fn << std::endl; + + delete[] arr; +} \ No newline at end of file diff --git a/Sem. 03/array_of_students_write.cpp b/Sem. 03/array_of_students_write.cpp new file mode 100644 index 0000000..3802bf8 --- /dev/null +++ b/Sem. 03/array_of_students_write.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +using namespace std; + +struct Student +{ + char name[30]; + int age; + int fn; +}; + +void initStudent(Student& st, const char* name, int age, int fn) +{ + strcpy(st.name, name); + st.age = age; + st.fn = fn; +} + +void saveToFile(const Student* students, size_t count, ofstream& file) +{ + file.write((const char*)students, count * sizeof(Student)); +} + + +int main() +{ + Student* arr = new Student[4]; + initStudent(arr[0], "ivan", 44, 1234); + initStudent(arr[1], "petur", 12, 765); + initStudent(arr[2], "alex", 15, 44); + initStudent(arr[3], "katerina", 19, 12134); + + ofstream file("students.dat", ios::binary); + saveToFile(arr, 4, file); + + delete[] arr; +} \ No newline at end of file -- cgit v1.3.1-23-gd82d