Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
||
ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
[18.217.144.32] |
|
Сообщ.
#1
,
|
|
|
Всем привет. Возник вопрос. Задача: сделать свой итератор и считывать инты из бинарного файла. Мой итератор пока вообще не работает, не заходит в цикл, хотя вроде логика есть. Какие нибудь советы?
#include <iostream> #include <cstdio> using namespace std; class IntFile { public: //int index = 0; int value; FILE* file; IntFile() {} ~IntFile() {} int mnumbers[10]; int mnumbers2[10]; int mnumbers3[10]; int getValue(int index) { fseek(file, 4*index, SEEK_SET); fread(&value, 4, 1, file); return value; } friend struct iterator; struct iterator { int index = 0; int value = 0; bool operator=(const iterator&other) const { return index == other.index; } bool operator!=(const iterator&other) const { return index!=other.index; } int &operator*() { //return value = IntFile::getValue(int index); } iterator&operator++() { this->index = index+1; } iterator&operator--() { index = index -1; } }; iterator begin() { fseek(file, 0, SEEK_SET); //index = 0; } iterator end() { fseek(file, 0, SEEK_END); //index = 9; } }; int main() { IntFile file; int A; // Getting numbers from user and putting them to array /* cout << "Enter your numbers: "; for ( int i = 0; i < 10; i++) { cin >> file.value; file.mnumbers[i] = file.value; //cout << file.mnumbers[i] << " "; } cout << endl; file.file = fopen("text.txt", "r+b"); fwrite(file.mnumbers,4,sizeof(file.mnumbers),file.file); fclose(file.file); */ for ( int i = 0; i < 10; i++) { file.mnumbers2[i] = 0; cout << file.mnumbers2[i] << " "; } file.file = fopen("text.txt", "r+b"); for (IntFile::iterator Iter = file.begin(); Iter != file.end(); ++Iter) { fread(file.mnumbers2,4,1,file.file); cout << " I " << endl; //cout << "Iterator: " << Iter; } cout << endl; A = file.getValue(9); cout << "A: " << A << endl; //cout << "array : "; for ( int i = 0; i < 10; i++) { cout << file.mnumbers2[i] << " "; } //////////////////////////////////////// fclose(file.file); return 0; } |
Сообщ.
#2
,
|
|
|
Надо изучить работу с файлами средствами C, потом изучить STL. После этого возможно будет понимание нецелесообразности использования идеи итераторов для файлов.
Основная проблема - обращение к итератору файла должно приводить и к операции seek, что нетипично для итератора. Если очень захотеть, можно сделать удобной (для программиста) работу через итератор с файлом как с массивом. Но природа чтения файла всё равно приведёт к нерациональной работе программы. |