Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.60/15: Рейтинг темы: голосов - 15, средняя оценка - 4.60
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
1

В файл записывается мусор. Подкорректировать код

31.01.2014, 00:21. Показов 2825. Ответов 27
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Нужна помощь!

В общем организована БД со структурами и целый перечень функций, которые её обслуживают. Всё работало, но что как-то пошло не так и теперь некорректно работает 4-ая функция: "Edit data". Находит, принимает, но после перезаписи затирает ёё мусором. Что интересно при редактировании 1-ой структуры - редактирует правильно саму структуру, но все остальное превращается в мусор. При редактировании последующих структур - затирает мусором выбранную и еще в добавок задевает последнее поле предыдущей структуры. 3-ий день не врублюсь никак в чем проблема. С радость выслушаю критику любого характера.

З.Ы.
Файл организован: 4 бита (кол-во всех структур в файле) -> https://www.cyberforum.ru/cgi-bin/latex.cgi?{struct}_{n}
Абракадабра в тексте программы - русские комментарии.
Написана в IDE С-Free 5.
Заранее премного благодарен!
Код сыроват.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
#include <iostream.h>
#include <ctime>
#include <fstream>
#include <iomanip.h>
#include <string.h>
 
    using namespace std;
    int check_data ();
    int inputdate();
    int inputint ();
    void Readfile ();
    void Makefile ();
    void Editfile();
    void Delefile ();
    void AddData ();
    void bbSearch();
    void seaPrice ();
    void seaString ();
    void seaRange();
    void inputchar ( char*, int);
    float inputfloat ();
    int mark =27;// for   s e t w ( m a r k ); 
    int cicl = 1;
        struct Date 
    {                   //date
    int year;       //of input  
    int month;
    int days;
    };  
    Date DateInput();
    void DateOut (struct Date );
    
struct bbase
{
    int large;              // large
    int ind;                    // id
    char name[100];         // Book's name
    float price;            //Book's price
    char pib[150];          //the author's name
    char kind[50];          //kind of genre
    Date when;           
    int sum;                //count
    
};
 
    
 
    
int main ()
{   
    check_data ();
    
    do
    {
    int chs; 
    cout<<"\nChoose function:\n"
        <<"1  -  M a k e   f i l e\n"
        <<"2  -  O u t p u t   d a t a\n"
        <<"3  -  D e l e t e   d a t a\n"
        <<"4  -  E d i t   d a t a \n"
        <<"5  -  A d d   d a t a \n"
        <<"6  -  S e a r c h   i n  b a s e\n"
        <<"0  -  E x i t\n"
        <<"Choose: "; chs = inputint ();
    switch (chs)
    {
        case 0: 
        {
            return (0); 
        }
        case 1: 
        {
            Makefile ();cout<<endl; break;
        }
        case 2:
        {
            Readfile();cout<<endl;  break;
        }
        case 3:
        {
            Delefile ();cout<<endl; break;
        }
        case 4:
        {
            Editfile();cout<<endl; break;
        }
        case 5:
        {
            AddData();cout<<endl;break;
        }
        case 6:
        {
            bbSearch();cout<<endl;break;
        }
        default:
        {
            cout<<"Error! Unknown number of function..."; break;
        }
    }
   }
   while (true);
 
 
return (0);
 
}
 
 
void Makefile ()
    {   
        struct bbase dat;
        ofstream f ("base1.txt", ios::out);
        if (!f)
        {
        cout<<" FAIL CANN'T BE OPEN";
        }
        else
        {
        cout<<"Enter size for data: ";
        int lar = inputint();
        f.write((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
{   
    cout<<i+1<<"-th input \n"; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    f.write((char*)&dat,sizeof(struct bbase));
}
    f.close();  
        }
}
 
//+++++++++++++++++ INPUT      I  N  T
int inputint ()
{    int A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
    if (A>=0)
    return (A);
    else
    {
    cout<<"Input integer >= 0\n";
    inputint(); 
    }
    
}
//+++++++++++++++++++++++++++++++++++++
 
//++++++++++++++input CAHR+++++++++++++
 
void inputchar (char *name, int const size)
{   
    cin.getline(name, size);
}
//++++++++++++++++++++++++++++++++++++++++
 
//+++++++++++++input FLOAT++++++++++++++++
float inputfloat ()
{    float A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
return (A);
}
//+++++++++++++++++++++++++++++++++++++++++
 
void Readfile ()
{
cout<< "\n\n\tFile contains: \n ";
    
    ifstream f ("base1.txt", ios::in);
    if (!f)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    struct bbase dat;
    int lar;
    f.read((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
        {
         f.read((char*)&dat, sizeof(struct bbase));
                                                    cout<<'\n';
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    f.close();
    
    
}
//+++++++++++++++++++++++++ CHECK 
int check_data ()
{   
    int che = 0;
    fstream f ("base1.txt", ios::in | ios::out);
    if (!f)
  {
    cout<<" FAIL CANN'T BE OPEN";
    return(0);
  }
  
    f.read((char*)&che, sizeof(bool));
    if (che>0) 
    {
        cout<<"Have data in database";
        return (1);
    }
    else
    {
        cout<<"Database is empty...\n"
        <<"You should start with 1-st function\n";
        return (0);
    }
    
}
//+++++++++++++++++++++++++++++++++++   
void Delefile ()
{       
        ofstream f ("base1.txt", ios::out);
        if (!f)
        {
            cout<<" FAIL CANN'T BE OPEN";
            return;
        }
        int lar = 0;
        f.write((char*)&lar, sizeof(bool));
        f.close ();
}
 
//+++++++++++++++ Â Â Î Ä   Ä À Ò Û +++++++++++++++++
Date DateInput ()
{   
    int C_year;
    int C_month;
    int C_days;
    bool ch_date = false;
    Date shad;
    do
    {
    cout<<"Date of input(YYYY.MM.DD): ";
    cin>>setw(4)>>C_year; //ãîä
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_month; //ìåñÿö
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_days; //äàòà
    if (C_year> 0 && C_month> 0 && C_month<= 12 && C_days > 0 && C_days <= 31)
    {   
        shad.year = C_year;
        shad.month = C_month;
        shad.days = C_days;
        ch_date = true; 
    }
    else 
    {
    cout<<"\nError #2 Probably, you did a mistake in date. Try again!\n";
    ch_date = false;
    }
    }
    while (ch_date != true);
    cout<<'\n';
  return (shad);
}
/////////////////////////////////////////////////////////////////
 
////////////////// D A T E    O U T P U T ////////////////////////
void DateOut (Date shad)                                        //
{                                                               //
    cout<<shad.year<<"."<<shad.month<<"."<<shad.days;           //
}                                                               //
//////////////////////////////////////////////////////////////////
 
 
 
void Editfile()
{   
    int n; char chs = 'y'; int count;
    ifstream el ("base1.txt", ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter ID: "; n=inputint();
    for (size_t i = 0; i <lar; i++)
    {   
        el.read((char*)&dat,sizeof(struct bbase));
        if (dat.ind == n)
        { 
    cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
    el.close();
    cout<<"Do you want change that string? ( y - YES else NO)"; 
    cin>>chs;
    if (chs == 'y')
    {
        char chs2;
        cout<<" Do you want to change wholly statement? ( y - YES else NO)";
        cin>>chs2;
////////////////////////////////////////////////////////////////////////////
    //      if (chs2 == 'y')
            {
            fstream er ("base1.txt", ios::in | ios::out); 
            if (!er)
            {
            cout<<" FAIL CANN'T BE OPEN"; return;
            }   
            struct bbase dat2;
        cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                       dat2.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat2.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat2.price = inputfloat ();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat2.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat2.kind, 50);
    cout<<setw(mark);                               dat2.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat2.sum = inputint();
    er.seekp (sizeof (int)+(sizeof(struct bbase)*i), ios::beg);
    er.write((char*)&dat2,sizeof(struct bbase));
    er.close();
    return;
    }
/*  else
        {   
            fstream el ("base1.txt", ios::in | ios::out); 
        if (!el)
        {
            cout<<" FAIL CANN'T BE OPEN"; return;
        }
        
        int X;
        cout<<"Enter number of line: ";
        cin>>X;
        switch (X)
        {
            case 1:
            {
                cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
                break;
            }
            case 2:
            {
                cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
                break;
            }
            case 3:
            {
                cout<<setw(mark)<<"Price: ";                    dat.price = inputfloat ();
                break;
            }
            case 4:
            {
                cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
                break;
            }
            case 5:
            {
                cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
                break;
            }
            case 6:
            {
                cout<<setw(mark);                               dat.when = DateInput();
                break;
            }
            case 7:
            {
                cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
                break;
            }
            default:
            {
            cout<<"Wrong number of line\n";
            break;
            }
    
        }   // end of switch (X)
        el.seekp (sizeof(bool)+ sizeof (int)+sizeof (struct bbase)*(i), ios::beg);
        el.write((char*)&dat,sizeof(struct bbase));
        el.close();
        return; 
        }   // end of else
        */
        }   // Wholly statment or not
        
    
    } //  I F ()
    } // FOR 
    cout<< "\n Unknown ID...";
}
 
void AddData ()
{   int n=0; int lar;
    cout<<"How much do you want to add?"<<endl;
    cout<<"Size: "; n=inputint ();
        fstream la ("base1.txt", ios::in | ios::out);
    if (!la)
        cout<<" FAIL CANN'T BE OPEN\n";
        else 
        la.read((char*)&lar,sizeof(int));
        
    lar+=n; 
    la.seekp(ios::beg);
    la.write((char*)&lar, sizeof (int));
    la.close();
    ofstream  em ("base1.txt", ios::app); 
    if (!em)
    {
    cout<<" FAIL CANN'T BE OPEN"; return;
    }
    for (size_t i = 0; i<n; i++)
    {struct bbase dat; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    em.write((char*)&dat,sizeof (struct bbase)); 
    }
    em.close();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////SEARCH SECTOR///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void bbSearch  ()
{   int ch;
    cout<<"Whar do you want to search? \n"
    <<"1 - In pursuant Price \n"
    <<"2 - Autors, genre, book's naem\n"
    <<"3 - In pursuant amount range\n"
    <<"0 - EXIT\n";
    cin>> ch;
    switch (ch)
    {
        case 1:
        {
        seaPrice ();break;
        }
        case 2:
        {
        seaString ();break;
        }
        case 3:
        {
        seaRange(); break;
        }
        case 0: return;
        
        default:{cout<<"Unkown funcion..."; break;}
    }
    
}
 
void seaPrice ()
{   int range;int n=0;
    ifstream el ("base1.txt", ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter Price: "; n=inputint();
    cout<<"1 - cheaper then '"<<n<<"', 2 - more \n"; cin>>range; 
    switch (range)
    {
        case 1:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price <= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;}// case 1
        
        case 2:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price >= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;} // case 2
        default: {cout<<"Unknown function...\n";break;}
  }// end of switch
  el.close();
} // end of seaPrice()  
 
void seaString ()
{   int lar;
    int ch;
    
    ifstream el ("base1.txt", ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
 
    el.read((char*)&lar, sizeof (int));
    
    cout<<" Enter function: \n";
    cout<<" 1 - Search books  in order autor\n"
        <<" 2 - Search books in ordet genre\n"
        <<" 3 - Search book's name\n"
        <<" 0 - EXIT\n";
    cin>>ch;
    switch (ch)
    {
        case 1: 
        {   
        char spib[150];
        
    cout<<"Enter Autor's name: ";
    cin.ignore();
    cin.getline(spib, 150);
    for (unsigned short int i = 0; i<lar; i++ )
    {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(spib,dat.pib) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
        break;} // end of case 1 for autors name
        case 2:
        {
        char skind[50];
        cout<<"Enter genre: "; 
        cin.ignore();
        cin.getline(skind,50);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(skind,dat.kind) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for
        break;} // end of case 2 for kind
        case 3: 
        {
        char sname[100];
        cout<<"Enter book's name: "; 
        cin.ignore();
        cin.getline(sname,100);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(sname,dat.name) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for 
        }
        case 0:
        {   el.close ();
            return; 
        }
        default:{cout<<"Unknown function...";break;}
    }       // end of switch
    el.close ();
}
 
void seaRange ()
{   
    unsigned a =0; unsigned b= 0;
    cout<<"Enter range for amount, for example (1-100)\n"
    <<"__"; 
    cout<<setw(4);cin>>a;cin.ignore();cout<<setw(4);cin>>b;
    ifstream el ("base1.txt", ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    
    el.read((char*)&lar, sizeof(int));
    for (unsigned i = 0; i<lar; i++)
    {   struct bbase dat;
        el.read((char*)&dat, sizeof(bbase));
        if (dat.sum>= a && dat.sum<=b)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
 
}
Вложения
Тип файла: rar kypc_01.rar (3.5 Кб, 5 просмотров)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
31.01.2014, 00:21
Ответы с готовыми решениями:

В файл записывается мусор
Добрый вечер! Почему при записи в бинарный файл, в файл записывается мусор и соответственно...

Записывается мусор в файл
Здравствуйте, есть следующий код для вывода дефолтных значений в файл: #include &lt;iostream&gt;...

В файл записывается мусор
Я запутался с записью в файл. Короче вот часть кода int bufer; //он заполнен числами ... FILE...

Из EditText в БД записывается мусор
При сохранении данных из EditText в БД, получается вон та фигня, что на картинке: Код: for (int...

27
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 00:53 2
Для начала... Файлы пишите/читаете бинарными методами, а открываете файлы в текстовом режиме.
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 00:59  [ТС] 3
Если можно мануал по этим методам под С++, а то Си я то понимаю разницу, а вот на С++ не уловил.
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 01:06 4
Мануалов море... Хотя бы здесь посмотрите: http://ci-plus-plus-snachala.ru/?p=84
Поисковиком пользуйтесь.
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 01:25  [ТС] 5
Спасибо, таких действительно больше, чем хотелось бы, но я так и не понял что имелось ввиду пишите/читаете/открываете. Файл хоть и текстовый, но содержание его не меняется, что .txt , что .dat там бинарный код или шестнадцатеричный, в общем не это важно. Можно пжл конкретней немного в чем моя ошибка. (не на строку указывать, а на ошибку в подходе работы с файлом). Просто сижу тут с Дейтлом и не пойму в чем проблема.
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 01:35 6
Цитата Сообщение от GraBLYA Посмотреть сообщение
Просто сижу тут с Дейтлом
Если в Дейтлом, то читайте, в главе 17: "Произвольная запись данных в файл произвольного доступа".
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 01:37  [ТС] 7
Цитата Сообщение от alsav22 Посмотреть сообщение
Если в Дейтлом, то читайте, в главе 17: "Файлы произвольного доступа".
Уже 3-ий раз, но я не пойму почему мусор пишет. 3-ем издании так точно, щас в 5-ом просмотрю.
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 01:43 8
Цитата Сообщение от GraBLYA Посмотреть сообщение
Уже 3-ий раз,
Что уже третий раз? Если читаете третий раз, то почему файлы открываете в текстовом режиме, а пишите/читаете бинарными методами?

Добавлено через 1 минуту
Цитата Сообщение от GraBLYA Посмотреть сообщение
но я не пойму почему мусор пишет.
Мусор может писать и по другоей причине, но сначала нужно это правильно сделать, а потом дальше идти.
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 02:05  [ТС] 9
Тобишь в идеале я должен писать поток, если открывать так же (текстовым) ? Ну или же открывать бинарным, что бы писать тем же способом?!
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 02:37 10
Цитата Сообщение от GraBLYA Посмотреть сообщение
Тобишь в идеале я должен писать поток, если открывать так же (текстовым) ? Ну или же открывать бинарным, что бы писать тем же способом?!
Не в идеале, а просто нужно так делать. В данном случае, просто допишите режим открытия для файлов.
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 02:39  [ТС] 11
Дейтл 3-е издание 761-762 страница. Вроде ему ничего не мешает использовать ios::in | ios::out и писать тем же способом, что и я. Но наверно Страуструп ему позвонил и сказал "
Цитата Сообщение от alsav22 Посмотреть сообщение
Файлы пишите/читаете бинарными методами, а открываете файлы в текстовом режиме.
он все понял с 10-го раза и уже в 5-м издании он дописывает "ios::binary", но и в добавок использует еще свои наращенные классы, что не дает мне до конца понять ход операций, но все же в общих чертах ничего не изменилось, если не считать дополнительный параметр.
Добавил параметр и изменилось - ничего.
З.Ы.
Скорее всего я недопонял чем это может помочь мне в поисках решения моей проблемки.
Можно ли поинтересоваться: каким образом производить произвольный доступ в текстовом файле? Строчки считать по "\0" или как?
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 02:54 12
Цитата Сообщение от GraBLYA Посмотреть сообщение
Скорее всего я недопонял чем это может помочь мне в поисках решения моей проблемки.
Про это я уже написал:
Цитата Сообщение от alsav22 Посмотреть сообщение
Мусор может писать и по другоей причине, но сначала нужно это правильно сделать, а потом дальше идти.
Цитата Сообщение от GraBLYA Посмотреть сообщение
Добавил параметр и изменилось - ничего.
Изменённый код нужно выкладывать. Ясновидящих тут нет.

Добавлено через 1 минуту
Цитата Сообщение от GraBLYA Посмотреть сообщение
каким образом производить произвольный доступ в текстовом файле?
Читатйе Дейтела, там всё должно быть написано (если нет, то есть много других книг).
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 23:08  [ТС] 13
Цитата Сообщение от alsav22 Посмотреть сообщение
Про это я уже написал:


Изменённый код нужно выкладывать. Ясновидящих тут нет.

Добавлено через 1 минуту

Читатйе Дейтела, там всё должно быть написано (если нет, то есть много других книг).
Если бы в книгах были все ответы, то надобность в форуме просто отпала бы.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
#include <iostream.h>
#include <ctime>
#include <fstream>
#include <iomanip.h>
#include <string.h>
/*
 Áàçà äàííûõ îðãàíèçîâàíà òàêèì îáðàçîì:
 ôàéë(áèòû ðåæèìà full/empty, áèòû ðàçìåðà áàçû(large), 1-àÿ ñòðóêòóðà...) 
*/
    using namespace std;
    int check_data ();
    int inputdate();
    int inputint ();
    void Readfile ();
    void Makefile ();
    void Editfile();
    void Delefile ();
    void AddData ();
    void bbSearch();
    void seaPrice ();
    void seaString ();
    void seaRange();
    void inputchar ( char*, int);
    float inputfloat ();
    const char fname [10]= {"base1.dat"};
    int mark =27;// for   s e t w ( m a r k ); 
    int cicl = 1;
        struct Date 
    {                   //date
    int year;       //of input  
    int month;
    int days;
    };  
    Date DateInput();
    void DateOut (struct Date );
    
struct bbase
{
    int large;              // large
    int ind;                    // id
    char name[100];         // Book's name
    float price;            //Book's price
    char pib[150];          //the author's name
    char kind[50];          //kind of genre
    Date when;           
    int sum;                //count
    
};
 
    
 
    
int main ()
{   
    check_data ();
    
    do
    {
    int chs; 
    cout<<"\nChoose function:\n"
        <<"1  -  M a k e   f i l e\n"
        <<"2  -  O u t p u t   d a t a\n"
        <<"3  -  D e l e t e   d a t a\n"
        <<"4  -  E d i t   d a t a \n"
        <<"5  -  A d d   d a t a \n"
        <<"6  -  S e a r c h   i n  b a s e\n"
        <<"0  -  E x i t\n"
        <<"Choose: "; chs = inputint ();
    switch (chs)
    {
        case 0: 
        {
            return (0); 
        }
        case 1: 
        {
            Makefile ();cout<<endl; break;
        }
        case 2:
        {
            Readfile();cout<<endl;  break;
        }
        case 3:
        {
            Delefile ();cout<<endl; break;
        }
        case 4:
        {
            Editfile();cout<<endl; break;
        }
        case 5:
        {
            AddData();cout<<endl;break;
        }
        case 6:
        {
            bbSearch();cout<<endl;break;
        }
        default:
        {
            cout<<"Error! Unknown number of function..."; break;
        }
    }
   }
   while (true);
 
 
return (0);
 
}
 
 
void Makefile ()
    {   
        struct bbase dat;
        ofstream f (fname, ios::out);
        if (!f)
        {
        cout<<" FAIL CANN'T BE OPEN";
        }
        else
        {
        cout<<"Enter size for data: ";
        int lar = inputint();
        f.write((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
{   
    cout<<i+1<<"-th input \n"; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    f.write((char*)&dat,sizeof(struct bbase));
}
    f.close();  
        }
}
 
//+++++++++++++++++ INPUT      I  N  T
int inputint ()
{    int A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
    if (A>=0)
    return (A);
    else
    {
    cout<<"Input integer >= 0\n";
    inputint(); 
    }
    
}
//+++++++++++++++++++++++++++++++++++++
 
//++++++++++++++input CAHR+++++++++++++
 
void inputchar (char *name, int const size)
{   
    cin.getline(name, size);
}
//++++++++++++++++++++++++++++++++++++++++
 
//+++++++++++++input FLOAT++++++++++++++++
float inputfloat ()
{    float A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
return (A);
}
//+++++++++++++++++++++++++++++++++++++++++
 
void Readfile ()
{
cout<< "\n\n\tFile contains: \n ";
    
    ifstream f (fname, ios::in);
    if (!f)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    struct bbase dat;
    int lar;
    f.read((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
        {
         f.read((char*)&dat, sizeof(struct bbase));
                                                    cout<<'\n';
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    f.close();
    
    
}
//+++++++++++++++++++++++++ CHECK 
int check_data ()
{   
    int che = 0;
    fstream f (fname, ios::in | ios::out);
    if (!f)
  {
    cout<<" FAIL CANN'T BE OPEN";
    return(0);
  }
  
    f.read((char*)&che, sizeof(bool));
    if (che>0) 
    {
        cout<<"Have data in database";
        return (1);
    }
    else
    {
        cout<<"Database is empty...\n"
        <<"You should start with 1-st function\n";
        return (0);
    }
    
}
//+++++++++++++++++++++++++++++++++++   
void Delefile ()
{       
        ofstream f (fname, ios::out);
        if (!f)
        {
            cout<<" FAIL CANN'T BE OPEN";
            return;
        }
        int lar = 0;
        f.write((char*)&lar, sizeof(bool));
        f.close ();
}
 
//+++++++++++++++ Â Â Î Ä   Ä À Ò Û +++++++++++++++++
Date DateInput ()
{   
    int C_year;
    int C_month;
    int C_days;
    bool ch_date = false;
    Date shad;
    do
    {
    cout<<"Date of input(YYYY.MM.DD): ";
    cin>>setw(4)>>C_year; //ãîä
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_month; //ìåñÿö
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_days; //äàòà
    if (C_year> 0 && C_month> 0 && C_month<= 12 && C_days > 0 && C_days <= 31)
    {   
        shad.year = C_year;
        shad.month = C_month;
        shad.days = C_days;
        ch_date = true; 
    }
    else 
    {
    cout<<"\nError #2 Probably, you did a mistake in date. Try again!\n";
    ch_date = false;
    }
    }
    while (ch_date != true);
    cout<<'\n';
  return (shad);
}
/////////////////////////////////////////////////////////////////
 
////////////////// D A T E    O U T P U T ////////////////////////
void DateOut (Date shad)                                        //
{                                                               //
    cout<<shad.year<<"."<<shad.month<<"."<<shad.days;           //
}                                                               //
//////////////////////////////////////////////////////////////////
 
 
 
void Editfile()
{   
    int n; char chs = 'y'; int count;
    ifstream el (fname, ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter ID: "; n=inputint();
    for (size_t i = 0; i <lar; i++)
    {   
        el.read((char*)&dat,sizeof(struct bbase));
        if (dat.ind == n)
        { 
    cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
    el.close();
    cout<<"Do you want change that string? ( y - YES else NO)"; 
    cin>>chs;
    if (chs == 'y')
    {
        char chs2;
        cout<<" Do you want to change wholly statement? ( y - YES else NO)";
        cin>>chs2;
////////////////////////////////////////////////////////////////////////////
    //      if (chs2 == 'y')
            {
            fstream er (fname, ios::binary | ios::in | ios::out); 
            if (!er)
            {
            cout<<" FAIL CANN'T BE OPEN"; return;
            }   
            struct bbase dat2;
        cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                       dat2.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat2.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat2.price = inputfloat ();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat2.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat2.kind, 50);
    cout<<setw(mark);                               dat2.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat2.sum = inputint();
    er.seekp (sizeof (int)+(sizeof(dat2)*i), ios::beg);
    er.write((char*)&dat2,sizeof(struct bbase));
    er.close();
    return;
    }
/*  else
        {   
            fstream el ("base1.txt", ios::in | ios::out); 
        if (!el)
        {
            cout<<" FAIL CANN'T BE OPEN"; return;
        }
        
        int X;
        cout<<"Enter number of line: ";
        cin>>X;
        switch (X)
        {
            case 1:
            {
                cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
                break;
            }
            case 2:
            {
                cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
                break;
            }
            case 3:
            {
                cout<<setw(mark)<<"Price: ";                    dat.price = inputfloat ();
                break;
            }
            case 4:
            {
                cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
                break;
            }
            case 5:
            {
                cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
                break;
            }
            case 6:
            {
                cout<<setw(mark);                               dat.when = DateInput();
                break;
            }
            case 7:
            {
                cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
                break;
            }
            default:
            {
            cout<<"Wrong number of line\n";
            break;
            }
    
        }   // end of switch (X)
        el.seekp (sizeof(bool)+ sizeof (int)+sizeof (struct bbase)*(i), ios::beg);
        el.write((char*)&dat,sizeof(struct bbase));
        el.close();
        return; 
        }   // end of else
        */
        }   // Wholly statment or not
        
    
    } //  I F ()
    } // FOR 
    cout<< "\n Unknown ID...";
}
 
void AddData ()
{   int n=0; int lar;
    cout<<"How much do you want to add?"<<endl;
    cout<<"Size: "; n=inputint ();
        fstream la (fname, ios::in | ios::out | ios::binary);
    if (!la)
        cout<<" FAIL CANN'T BE OPEN\n";
        else 
        la.read((char*)&lar,sizeof(int));
        
    lar+=n; 
    la.seekp(0);
    la.write((char*)&lar, sizeof (int));
    la.close();
    ofstream  em (fname, ios::app); 
    if (!em)
    {
    cout<<" FAIL CANN'T BE OPEN"; return;
    }
    for (size_t i = 0; i<n; i++)
    {struct bbase dat; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    em.write((char*)&dat,sizeof (struct bbase)); 
    }
    em.close();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////SEARCH SECTOR///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void bbSearch  ()
{   int ch;
    cout<<"Whar do you want to search? \n"
    <<"1 - In pursuant Price \n"
    <<"2 - Autors, genre, book's naem\n"
    <<"3 - In pursuant amount range\n"
    <<"0 - EXIT\n";
    cin>> ch;
    switch (ch)
    {
        case 1:
        {
        seaPrice ();break;
        }
        case 2:
        {
        seaString ();break;
        }
        case 3:
        {
        seaRange(); break;
        }
        case 0: return;
        
        default:{cout<<"Unkown funcion..."; break;}
    }
    
}
 
void seaPrice ()
{   int range;int n=0;
    ifstream el (fname, ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter Price: "; n=inputint();
    cout<<"1 - cheaper then '"<<n<<"', 2 - more \n"; cin>>range; 
    switch (range)
    {
        case 1:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price <= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;}// case 1
        
        case 2:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price >= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;} // case 2
        default: {cout<<"Unknown function...\n";break;}
  }// end of switch
  el.close();
} // end of seaPrice()  
 
void seaString ()
{   int lar;
    int ch;
    
    ifstream el (fname, ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
 
    el.read((char*)&lar, sizeof (int));
    
    cout<<" Enter function: \n";
    cout<<" 1 - Search books  in order autor\n"
        <<" 2 - Search books in ordet genre\n"
        <<" 3 - Search book's name\n"
        <<" 0 - EXIT\n";
    cin>>ch;
    switch (ch)
    {
        case 1: 
        {   
        char spib[150];
        
    cout<<"Enter Autor's name: ";
    cin.ignore();
    cin.getline(spib, 150);
    for (unsigned short int i = 0; i<lar; i++ )
    {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(spib,dat.pib) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
        break;} // end of case 1 for autors name
        case 2:
        {
        char skind[50];
        cout<<"Enter genre: "; 
        cin.ignore();
        cin.getline(skind,50);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(skind,dat.kind) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for
        break;} // end of case 2 for kind
        case 3: 
        {
        char sname[100];
        cout<<"Enter book's name: "; 
        cin.ignore();
        cin.getline(sname,100);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(sname,dat.name) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for 
        }
        case 0:
        {   el.close ();
            return; 
        }
        default:{cout<<"Unknown function...";break;}
    }       // end of switch
    el.close ();
}
 
void seaRange ()
{   
    unsigned a =0; unsigned b= 0;
    cout<<"Enter range for amount, for example (1-100)\n"
    <<"__"; 
    cout<<setw(4);cin>>a;cin.ignore();cout<<setw(4);cin>>b;
    ifstream el ("base1.txt", ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    
    el.read((char*)&lar, sizeof(int));
    for (unsigned i = 0; i<lar; i++)
    {   struct bbase dat;
        el.read((char*)&dat, sizeof(bbase));
        if (dat.sum>= a && dat.sum<=b)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
 
}
Все функции работают нормально, но после попытки редактирования, файл становится непригодным. Удалить -> заполнить и все функции снова работают корректно.
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 23:15 14
Цитата Сообщение от GraBLYA Посмотреть сообщение
ifstream el (fname, ios::in);
Цитата Сообщение от GraBLYA Посмотреть сообщение
ofstream f (fname, ios::out);
Цитата Сообщение от GraBLYA Посмотреть сообщение
ifstream f (fname, ios::in);
Цитата Сообщение от GraBLYA Посмотреть сообщение
fstream f (fname, ios::in | ios::out);
Цитата Сообщение от GraBLYA Посмотреть сообщение
ofstream f (fname, ios::out);
Цитата Сообщение от GraBLYA Посмотреть сообщение
ifstream el (fname, ios::in);
и т.д.
Это и называется:
Цитата Сообщение от GraBLYA Посмотреть сообщение
Добавил параметр и изменилось - ничего.
Да?

Добавлено через 1 минуту
Цитата Сообщение от GraBLYA Посмотреть сообщение
Если бы в книга были все ответы, то надобность в форуме отпала бы.
Про все не говорю, но про эти точно есть:
Цитата Сообщение от GraBLYA Посмотреть сообщение
каким образом производить произвольный доступ в текстовом файле? Строчки считать по "\0" или как?
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
31.01.2014, 23:46  [ТС] 15
Цитата Сообщение от alsav22 Посмотреть сообщение
и т.д.
Это и называется:

Да?

Добавлено через 1 минуту

Про все не говорю, но про эти точно есть:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
#include <iostream.h>
#include <ctime>
#include <fstream>
#include <iomanip.h>
#include <string.h>
/*
 Áàçà äàííûõ îðãàíèçîâàíà òàêèì îáðàçîì:
 ôàéë(áèòû ðåæèìà full/empty, áèòû ðàçìåðà áàçû(large), 1-àÿ ñòðóêòóðà...) 
*/
    using namespace std;
    int check_data ();
    int inputdate();
    int inputint ();
    void Readfile ();
    void Makefile ();
    void Editfile();
    void Delefile ();
    void AddData ();
    void bbSearch();
    void seaPrice ();
    void seaString ();
    void seaRange();
    void inputchar ( char*, int);
    float inputfloat ();
    const char fname [10]= {"base1.dat"};
    int mark =27;// for   s e t w ( m a r k ); 
    int cicl = 1;
        struct Date 
    {                   //date
    int year;       //of input  
    int month;
    int days;
    };  
    Date DateInput();
    void DateOut (struct Date );
    
struct bbase
{
    int large;              // large
    int ind;                    // id
    char name[100];         // Book's name
    float price;            //Book's price
    char pib[150];          //the author's name
    char kind[50];          //kind of genre
    Date when;           
    int sum;                //count
    
};
 
    
 
    
int main ()
{   
    check_data ();
    
    do
    {
    int chs; 
    cout<<"\nChoose function:\n"
        <<"1  -  M a k e   f i l e\n"
        <<"2  -  O u t p u t   d a t a\n"
        <<"3  -  D e l e t e   d a t a\n"
        <<"4  -  E d i t   d a t a \n"
        <<"5  -  A d d   d a t a \n"
        <<"6  -  S e a r c h   i n  b a s e\n"
        <<"0  -  E x i t\n"
        <<"Choose: "; chs = inputint ();
    switch (chs)
    {
        case 0: 
        {
            return (0); 
        }
        case 1: 
        {
            Makefile ();cout<<endl; break;
        }
        case 2:
        {
            Readfile();cout<<endl;  break;
        }
        case 3:
        {
            Delefile ();cout<<endl; break;
        }
        case 4:
        {
            Editfile();cout<<endl; break;
        }
        case 5:
        {
            AddData();cout<<endl;break;
        }
        case 6:
        {
            bbSearch();cout<<endl;break;
        }
        default:
        {
            cout<<"Error! Unknown number of function..."; break;
        }
    }
   }
   while (true);
 
 
return (0);
 
}
 
 
void Makefile ()
    {   
        struct bbase dat;
        ofstream f (fname, ios::out | ios::binary);
        if (!f)
        {
        cout<<" FAIL CANN'T BE OPEN";
        }
        else
        {
        cout<<"Enter size for data: ";
        int lar = inputint();
        f.write((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
{   
    cout<<i+1<<"-th input \n"; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    f.write((char*)&dat,sizeof(struct bbase));
}
    f.close();  
        }
}
 
//+++++++++++++++++ INPUT      I  N  T
int inputint ()
{    int A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
    if (A>=0)
    return (A);
    else
    {
    cout<<"Input integer >= 0\n";
    inputint(); 
    }
    
}
//+++++++++++++++++++++++++++++++++++++
 
//++++++++++++++input CAHR+++++++++++++
 
void inputchar (char *name, int const size)
{   
    cin.getline(name, size);
}
//++++++++++++++++++++++++++++++++++++++++
 
//+++++++++++++input FLOAT++++++++++++++++
float inputfloat ()
{    float A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
return (A);
}
//+++++++++++++++++++++++++++++++++++++++++
 
void Readfile ()
{
cout<< "\n\n\tFile contains: \n ";
    
    ifstream f (fname, ios::in);
    if (!f)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    struct bbase dat;
    int lar;
    f.read((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
        {
         f.read((char*)&dat, sizeof(struct bbase));
                                                    cout<<'\n';
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    f.close();
    
    
}
//+++++++++++++++++++++++++ CHECK 
int check_data ()
{   
    int che = 0;
    fstream f (fname, ios::in);
    if (!f)
  {
    cout<<" FAIL CANN'T BE OPEN";
    return(0);
  }
  
    f.read((char*)&che, sizeof(bool));
    if (che>0) 
    {
        cout<<"Have data in database";
        return (1);
    }
    else
    {
        cout<<"Database is empty...\n"
        <<"You should start with 1-st function\n";
        return (0);
    }
    
}
//+++++++++++++++++++++++++++++++++++   
void Delefile ()
{       
        ofstream f (fname, ios::out);
        if (!f)
        {
            cout<<" FAIL CANN'T BE OPEN";
            return;
        }
        int lar = 0;
        f.write((char*)&lar, sizeof(bool));
        f.close ();
}
 
//+++++++++++++++ Â Â Î Ä   Ä À Ò Û +++++++++++++++++
Date DateInput ()
{   
    int C_year;
    int C_month;
    int C_days;
    bool ch_date = false;
    Date shad;
    do
    {
    cout<<"Date of input(YYYY.MM.DD): ";
    cin>>setw(4)>>C_year; //ãîä
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_month; //ìåñÿö
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_days; //äàòà
    if (C_year> 0 && C_month> 0 && C_month<= 12 && C_days > 0 && C_days <= 31)
    {   
        shad.year = C_year;
        shad.month = C_month;
        shad.days = C_days;
        ch_date = true; 
    }
    else 
    {
    cout<<"\nError #2 Probably, you did a mistake in date. Try again!\n";
    ch_date = false;
    }
    }
    while (ch_date != true);
    cout<<'\n';
  return (shad);
}
/////////////////////////////////////////////////////////////////
 
////////////////// D A T E    O U T P U T ////////////////////////
void DateOut (Date shad)                                        //
{                                                               //
    cout<<shad.year<<"."<<shad.month<<"."<<shad.days;           //
}                                                               //
//////////////////////////////////////////////////////////////////
 
 
 
void Editfile()
{   
    int n; char chs = 'y'; int count;
    ifstream el (fname, ios::in);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter ID: "; n=inputint();
    for (size_t i = 0; i <lar; i++)
    {   
        el.read((char*)&dat,sizeof(struct bbase));
        if (dat.ind == n)
        { 
    cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
    el.close();
    cout<<"Do you want change that string? ( y - YES else NO)"; 
    cin>>chs;
    if (chs == 'y')
    {
        char chs2;
        cout<<" Do you want to change wholly statement? ( y - YES else NO)";
        cin>>chs2;
////////////////////////////////////////////////////////////////////////////
    //      if (chs2 == 'y')
            {
            fstream er (fname, ios::binary | ios::in | ios::out); 
            if (!er)
            {
            cout<<" FAIL CANN'T BE OPEN"; return;
            }   
            struct bbase dat2;
        cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                       dat2.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat2.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat2.price = inputfloat ();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat2.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat2.kind, 50);
    cout<<setw(mark);                               dat2.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat2.sum = inputint();
    er.seekp (sizeof (int)+(sizeof(dat2)*i), ios::beg);
    er.write((char*)&dat2,sizeof(struct bbase));
    er.close();
    return;
    }
 
/*  else
        {   
            fstream el ("base1.txt", ios::in | ios::out); 
        if (!el)
        {
            cout<<" FAIL CANN'T BE OPEN"; return;
        }
        
        int X;
        cout<<"Enter number of line: ";
        cin>>X;
        switch (X)
        {
            case 1:
            {
                cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
                break;
            }
            case 2:
            {
                cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
                break;
            }
            case 3:
            {
                cout<<setw(mark)<<"Price: ";                    dat.price = inputfloat ();
                break;
            }
            case 4:
            {
                cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
                break;
            }
            case 5:
            {
                cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
                break;
            }
            case 6:
            {
                cout<<setw(mark);                               dat.when = DateInput();
                break;
            }
            case 7:
            {
                cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
                break;
            }
            default:
            {
            cout<<"Wrong number of line\n";
            break;
            }
    
        }   // end of switch (X)
        el.seekp (sizeof(bool)+ sizeof (int)+sizeof (struct bbase)*(i), ios::beg);
        el.write((char*)&dat,sizeof(struct bbase));
        el.close();
        return; 
        }   // end of else
        */
    }   // Wholly statment or not
        
    
    } //  I F ()
    } // FOR 
    cout<< "\n Unknown ID...";
}
 
void AddData ()
{   int n=0; int lar;
    cout<<"How much do you want to add?"<<endl;
    cout<<"Size: "; n=inputint ();
        fstream la (fname, ios::in | ios::binary | ios::out);
    if (!la)
    {
        cout<<" FAIL CANN'T BE OPEN\n";
        return;
    }
        
        else 
        la.read((char*)&lar,sizeof(int));
        
    lar+=n; 
    la.seekp(0);
    la.write((char*)&lar, sizeof (int));
    la.close();
    ofstream  em (fname, ios::app ); 
    if (!em)
    {
    cout<<" FAIL CANN'T BE OPEN"; return;
    }
    for (size_t i = 0; i<n; i++)
    {struct bbase dat; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    em.write((char*)&dat,sizeof (struct bbase)); 
    }
    em.close();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////SEARCH SECTOR///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void bbSearch  ()
{   int ch;
    cout<<"Whar do you want to search? \n"
    <<"1 - In pursuant Price \n"
    <<"2 - Autors, genre, book's naem\n"
    <<"3 - In pursuant amount range\n"
    <<"0 - EXIT\n";
    cin>> ch;
    switch (ch)
    {
        case 1:
        {
        seaPrice ();break;
        }
        case 2:
        {
        seaString ();break;
        }
        case 3:
        {
        seaRange(); break;
        }
        case 0: return;
        
        default:{cout<<"Unkown funcion..."; break;}
    }
    
}
 
void seaPrice ()
{   int range;int n=0;
    ifstream el (fname, ios::in| ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter Price: "; n=inputint();
    cout<<"1 - cheaper then '"<<n<<"', 2 - more \n"; cin>>range; 
    switch (range)
    {
        case 1:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price <= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;}// case 1
        
        case 2:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price >= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;} // case 2
        default: {cout<<"Unknown function...\n";break;}
  }// end of switch
  el.close();
} // end of seaPrice()  
 
void seaString ()
{   int lar;
    int ch;
    
    ifstream el (fname, ios::in| ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
 
    el.read((char*)&lar, sizeof (int));
    
    cout<<" Enter function: \n";
    cout<<" 1 - Search books  in order autor\n"
        <<" 2 - Search books in ordet genre\n"
        <<" 3 - Search book's name\n"
        <<" 0 - EXIT\n";
    cin>>ch;
    switch (ch)
    {
        case 1: 
        {   
        char spib[150];
        
    cout<<"Enter Autor's name: ";
    cin.ignore();
    cin.getline(spib, 150);
    for (unsigned short int i = 0; i<lar; i++ )
    {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(spib,dat.pib) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
        break;} // end of case 1 for autors name
        case 2:
        {
        char skind[50];
        cout<<"Enter genre: "; 
        cin.ignore();
        cin.getline(skind,50);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(skind,dat.kind) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for
        break;} // end of case 2 for kind
        case 3: 
        {
        char sname[100];
        cout<<"Enter book's name: "; 
        cin.ignore();
        cin.getline(sname,100);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(sname,dat.name) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for 
        }
        case 0:
        {   el.close ();
            return; 
        }
        default:{cout<<"Unknown function...";break;}
    }       // end of switch
    el.close ();
}
 
void seaRange ()
{   
    unsigned a =0; unsigned b= 0;
    cout<<"Enter range for amount, for example (1-100)\n"
    <<"__"; 
    cout<<setw(4);cin>>a;cin.ignore();cout<<setw(4);cin>>b;
    ifstream el ("base1.txt", ios::in| ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    
    el.read((char*)&lar, sizeof(int));
    for (unsigned i = 0; i<lar; i++)
    {   struct bbase dat;
        el.read((char*)&dat, sizeof(bbase));
        if (dat.sum>= a && dat.sum<=b)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
 
}
Немного ситуация улучшилась, но в определенный момент проблема возвращается. Когда именно - я никак вычислить не могу. 1 раз заполняет мусором, когда редактирую 1-ую запись из 2-х, после перезаписи - все нормально, другой раз после многочисленных однотипных операций вдруг опять мусор.
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
31.01.2014, 23:55 16
Лучший ответ Сообщение было отмечено GraBLYA как решение

Решение

Цитата Сообщение от GraBLYA Посмотреть сообщение
fstream f (fname, ios::in);
Цитата Сообщение от GraBLYA Посмотреть сообщение
ofstream f (fname, ios::out);
Цитата Сообщение от GraBLYA Посмотреть сообщение
ifstream el (fname, ios::in);
???

Не по теме:

Начинает надоедать.

1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
01.02.2014, 01:05  [ТС] 17
Цитата Сообщение от alsav22 Посмотреть сообщение
???

Не по теме:

Начинает надоедать.

При добавлении абсолютно во все функции открытия - вышли из строя все функции. Я оставил эти функции без изменения т.к. в них не нужен произвольный доступ к файлу.

Добавлено через 45 минут
В общем в виду хаотичности корректировок не могу сказать точно что помогло, но все же ошибка проскакивает, хотя вызвать её не всегда получается. ПРЕМНОГО благодарен за наводки, alsav22. Надеюсь еще спишемся
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#include <iostream.h>
#include <ctime>
#include <fstream>
#include <iomanip.h>
#include <string.h>
/*
 Áàçà äàííûõ îðãàíèçîâàíà òàêèì îáðàçîì:
 ôàéë(áèòû ðåæèìà full/empty, áèòû ðàçìåðà áàçû(large), 1-àÿ ñòðóêòóðà...) 
*/
    using namespace std;
    int check_data ();
    int inputdate();
    int inputint ();
    void Readfile ();
    void Makefile ();
    void Editfile();
    void Delefile ();
    void AddData ();
    void bbSearch();
    void seaPrice ();
    void seaString ();
    void seaRange();
    void inputchar ( char*, int);
    float inputfloat ();
    const char fname [10]= {"base1.dat"};
    int mark =27;// for   s e t w ( m a r k ); 
    int cicl = 1;
        struct Date 
    {                   //date
    int year;       //of input  
    int month;
    int days;
    };  
    Date DateInput();
    void DateOut (struct Date );
    
struct bbase
{
    int large;              // large
    int ind;                    // id
    char name[100];         // Book's name
    float price;            //Book's price
    char pib[150];          //the author's name
    char kind[50];          //kind of genre
    Date when;           
    int sum;                //count
    
};
 
    
 
    
int main ()
{   
    check_data ();
    
    do
    {
    int chs; 
    cout<<"\nChoose function:\n"
        <<"1  -  M a k e   f i l e\n"
        <<"2  -  O u t p u t   d a t a\n"
        <<"3  -  D e l e t e   d a t a\n"
        <<"4  -  E d i t   d a t a \n"
        <<"5  -  A d d   d a t a \n"
        <<"6  -  S e a r c h   i n  b a s e\n"
        <<"0  -  E x i t\n"
        <<"Choose: "; chs = inputint ();
    switch (chs)
    {
        case 0: 
        {
            return (0); 
        }
        case 1: 
        {
            Makefile ();cout<<endl; break;
        }
        case 2:
        {
            Readfile();cout<<endl;  break;
        }
        case 3:
        {
            Delefile ();cout<<endl; break;
        }
        case 4:
        {
            Editfile();cout<<endl; break;
        }
        case 5:
        {
            AddData();cout<<endl;break;
        }
        case 6:
        {
            bbSearch();cout<<endl;break;
        }
        default:
        {
            cout<<"Error! Unknown number of function..."; break;
        }
    }
   }
   while (true);
 
 
return (0);
 
}
 
 
void Makefile ()
    {   
        struct bbase dat;
        ofstream f (fname, ios::out | ios::binary);
        if (!f)
        {
        cout<<" FAIL CANN'T BE OPEN";
        }
        else
        {
        cout<<"Enter size for data: ";
        int lar = inputint();
        f.write((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
{   
    cout<<i+1<<"-th input \n"; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    f.write((char*)&dat,sizeof(struct bbase));
}
    f.close();  
        }
}
 
//+++++++++++++++++ INPUT      I  N  T
int inputint ()
{    int A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
    if (A>=0)
    return (A);
    else
    {
    cout<<"Input integer >= 0\n";
    inputint(); 
    }
    
}
//+++++++++++++++++++++++++++++++++++++
 
//++++++++++++++input CAHR+++++++++++++
 
void inputchar (char *name, int const size)
{   
    cin.getline(name, size);
}
//++++++++++++++++++++++++++++++++++++++++
 
//+++++++++++++input FLOAT++++++++++++++++
float inputfloat ()
{    float A;
     while(!(cin>>A) || cin.get() != '\n') 
    {
        cout<<" You did a mistake\n";
        cin.clear(); 
        cin.sync();
        cout<<setw(20)<<"Repit: ";
    }
return (A);
}
//+++++++++++++++++++++++++++++++++++++++++
 
void Readfile ()
{
cout<< "\n\n\tFile contains: \n ";
    
    ifstream f (fname, ios::in | ios::binary);
    if (!f)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    struct bbase dat;
    int lar;
    f.read((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
        {
         f.read((char*)&dat, sizeof(struct bbase));
                                                    cout<<'\n';
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    f.close();
    
    
}
//+++++++++++++++++++++++++ CHECK 
int check_data ()
{   
    int che = 0;
    fstream f (fname, ios::in);
    if (!f)
  {
    cout<<" FAIL CANN'T BE OPEN";
    return(0);
  }
  
    f.read((char*)&che, sizeof(bool));
    if (che>0) 
    {
        cout<<"Have data in database";
        return (1);
    }
    else
    {
        cout<<"Database is empty...\n"
        <<"You should start with 1-st function\n";
        return (0);
    }
    
}
//+++++++++++++++++++++++++++++++++++   
void Delefile ()
{       
        ofstream f (fname, ios::out);
        if (!f)
        {
            cout<<" FAIL CANN'T BE OPEN";
            return;
        }
        int lar = 0;
        f.write((char*)&lar, sizeof(bool));
        f.close ();
}
 
//+++++++++++++++ Â Â Î Ä   Ä À Ò Û +++++++++++++++++
Date DateInput ()
{   
    int C_year;
    int C_month;
    int C_days;
    bool ch_date = false;
    Date shad;
    do
    {
    cout<<"Date of input(YYYY.MM.DD): ";
    cin>>setw(4)>>C_year; //ãîä
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_month; //ìåñÿö
    cin.ignore();    //òî÷êà
    cin>>setw(2)>>C_days; //äàòà
    if (C_year> 0 && C_month> 0 && C_month<= 12 && C_days > 0 && C_days <= 31)
    {   
        shad.year = C_year;
        shad.month = C_month;
        shad.days = C_days;
        ch_date = true; 
    }
    else 
    {
    cout<<"\nError #2 Probably, you did a mistake in date. Try again!\n";
    ch_date = false;
    }
    }
    while (ch_date != true);
    cout<<'\n';
  return (shad);
}
/////////////////////////////////////////////////////////////////
 
////////////////// D A T E    O U T P U T ////////////////////////
void DateOut (Date shad)                                        //
{                                                               //
    cout<<shad.year<<"."<<shad.month<<"."<<shad.days;           //
}                                                               //
//////////////////////////////////////////////////////////////////
 
 
 
void Editfile()
{   
    int n; char chs = 'y'; int count;
    ifstream el (fname, ios::in | ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter ID: "; n=inputint();
    for (size_t i = 0; i <lar; i++)
    {   
        el.read((char*)&dat,sizeof(struct bbase));
        if (dat.ind == n)
        { 
    cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
    el.close();
    cout<<"Do you want change that string? ( y - YES else NO)"; 
    cin>>chs;
    if (chs == 'y')
    {
        char chs2;
        cout<<" Do you want to change wholly statement? ( y - YES else NO)";
        cin>>chs2;
////////////////////////////////////////////////////////////////////////////
    //      if (chs2 == 'y')
            {
            fstream er (fname, ios::binary | ios::in | ios::out); 
            if (!er)
            {
            cout<<" FAIL CANN'T BE OPEN"; return;
            }   
            struct bbase dat2;
        cout<<"ID: "<<n<<"\n"; 
    cout<<setw(mark)<<"ID: ";                       dat2.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat2.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat2.price = inputfloat ();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat2.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat2.kind, 50);
    cout<<setw(mark);                               dat2.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat2.sum = inputint();
    er.seekp (sizeof (int)+(sizeof(dat2)*i), ios::beg);
    er.write((char*)&dat2,sizeof(struct bbase));
    er.close();
    return;
    }
 
/*  else
        {   
            fstream el ("base1.txt", ios::in | ios::out); 
        if (!el)
        {
            cout<<" FAIL CANN'T BE OPEN"; return;
        }
        
        int X;
        cout<<"Enter number of line: ";
        cin>>X;
        switch (X)
        {
            case 1:
            {
                cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
                break;
            }
            case 2:
            {
                cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
                break;
            }
            case 3:
            {
                cout<<setw(mark)<<"Price: ";                    dat.price = inputfloat ();
                break;
            }
            case 4:
            {
                cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
                break;
            }
            case 5:
            {
                cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
                break;
            }
            case 6:
            {
                cout<<setw(mark);                               dat.when = DateInput();
                break;
            }
            case 7:
            {
                cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
                break;
            }
            default:
            {
            cout<<"Wrong number of line\n";
            break;
            }
    
        }   // end of switch (X)
        el.seekp (sizeof(bool)+ sizeof (int)+sizeof (struct bbase)*(i), ios::beg);
        el.write((char*)&dat,sizeof(struct bbase));
        el.close();
        return; 
        }   // end of else
        */
    }   // Wholly statment or not
        
    
    } //  I F ()
    } // FOR 
    cout<< "\n Unknown ID...";
}
 
void AddData ()
{   int n=0; int lar;
    cout<<"How much do you want to add?"<<endl;
    cout<<"Size: "; n=inputint ();
        fstream la (fname,ios::out| ios::in | ios::binary);
    if (!la)
    {
        cout<<" FAIL CANN'T BE OPEN\n";
        return;
    }
        
        else 
        la.read((char*)&lar,sizeof(int));
        
    lar+=n; 
    la.seekp(0);
    la.write((char*)&lar, sizeof (int));
    la.close();
    
    for (size_t i = 0; i<n; i++)
    {
    ofstream  em (fname,ios::app | ios::binary); 
    if (!em)
    {
    cout<<" FAIL CANN'T BE OPEN"; return;
    }
    struct bbase dat; 
    cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
    cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
    cout<<setw(mark);                               dat.when = DateInput();
    cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
    em.write((char*)&dat,sizeof (struct bbase)); 
    em.close();
    }
    
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////SEARCH SECTOR///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void bbSearch  ()
{   int ch;
    cout<<"Whar do you want to search? \n"
    <<"1 - In pursuant Price \n"
    <<"2 - Autors, genre, book's naem\n"
    <<"3 - In pursuant amount range\n"
    <<"0 - EXIT\n";
    cin>> ch;
    switch (ch)
    {
        case 1:
        {
        seaPrice ();break;
        }
        case 2:
        {
        seaString ();break;
        }
        case 3:
        {
        seaRange(); break;
        }
        case 0: return;
        
        default:{cout<<"Unkown funcion..."; break;}
    }
    
}
 
void seaPrice ()
{   int range;int n=0;
    ifstream el (fname, ios::in| ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter Price: "; n=inputint();
    cout<<"1 - cheaper then '"<<n<<"', 2 - more \n"; cin>>range; 
    switch (range)
    {
        case 1:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price <= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;}// case 1
        
        case 2:
        {
            for (size_t i = 0; i <lar; i++)
    {       
            el.read((char*)&dat, sizeof(struct bbase));
            if (dat.price >= n)
            {cout<<endl;
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            }       
    }
        break;} // case 2
        default: {cout<<"Unknown function...\n";break;}
  }// end of switch
  el.close();
} // end of seaPrice()  
 
void seaString ()
{   int lar;
    int ch;
    
    ifstream el (fname, ios::in| ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
 
    el.read((char*)&lar, sizeof (int));
    
    cout<<" Enter function: \n";
    cout<<" 1 - Search books  in order autor\n"
        <<" 2 - Search books in ordet genre\n"
        <<" 3 - Search book's name\n"
        <<" 0 - EXIT\n";
    cin>>ch;
    switch (ch)
    {
        case 1: 
        {   
        char spib[150];
        
    cout<<"Enter Autor's name: ";
    cin.ignore();
    cin.getline(spib, 150);
    for (unsigned short int i = 0; i<lar; i++ )
    {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(spib,dat.pib) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
        break;} // end of case 1 for autors name
        case 2:
        {
        char skind[50];
        cout<<"Enter genre: "; 
        cin.ignore();
        cin.getline(skind,50);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(skind,dat.kind) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for
        break;} // end of case 2 for kind
        case 3: 
        {
        char sname[100];
        cout<<"Enter book's name: "; 
        cin.ignore();
        cin.getline(sname,100);
            for (unsigned short int i = 0; i<lar; i++ )
        {   
        struct bbase dat;
        el.read((char*)&dat,sizeof (bbase));
        if (stricmp(sname,dat.name) == 0)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
        }// for 
        }
        case 0:
        {   el.close ();
            return; 
        }
        default:{cout<<"Unknown function...";break;}
    }       // end of switch
    el.close ();
}
 
void seaRange ()
{   
    unsigned a =0; unsigned b= 0;
    cout<<"Enter range for amount, for example (1-100)\n"
    <<"__"; 
    cout<<setw(4);cin>>a;cin.ignore();cout<<setw(4);cin>>b;
    ifstream el ("base1.txt", ios::in| ios::binary);
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    
    el.read((char*)&lar, sizeof(int));
    for (unsigned i = 0; i<lar; i++)
    {   struct bbase dat;
        el.read((char*)&dat, sizeof(bbase));
        if (dat.sum>= a && dat.sum<=b)
        {
    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
        }
    }
 
}
0
5498 / 4893 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
01.02.2014, 02:54 18
Лучший ответ Сообщение было отмечено GraBLYA как решение

Решение

Цитата Сообщение от GraBLYA Посмотреть сообщение
Я оставил эти функции без изменения т.к. в них не нужен произвольный доступ к файлу.
Интересные рассуждения. Если не нужен произвольный метод доступа к файлу, то зачем используете методы произвольного доступа к файлу? Например:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
void Editfile()
{   
    int n; char chs = 'y'; int count;
    ifstream el (fname, ios::in); // открываете в текстовом режиме
    if (!el)
    {
    cout<<" FAIL CANN'T BE OPEN";
    return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int)); // читаете бинарным методом
...
Не нужен - не используйте.

Добавлено через 2 минуты
Цитата Сообщение от GraBLYA Посмотреть сообщение
При добавлении абсолютно во все функции открытия - вышли из строя все функции.
Вот и нужно было выяснить - почему? Если делаете, как нужно, и код перестаёт работать, значит код кривой.
И как следствие:
Цитата Сообщение от GraBLYA Посмотреть сообщение
но все же ошибка проскакивает, хотя вызвать её не всегда получается.
Добавлено через 5 минут
Вот ваш код, в котором, во всех случаях открытия файла, это делается в бинарном режиме. И почему-то нормально работает:

Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
#include <iostream>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
 
int check_data ();
int inputdate();
int inputint ();
void Readfile ();
void Makefile ();
void Editfile();
void Delefile ();
void AddData ();
void bbSearch();
void seaPrice ();
void seaString ();
void seaRange();
void inputchar ( char*, int);
float inputfloat ();
int mark =27;// for   s e t w ( m a r k ); 
int cicl = 1;
 
struct Date 
{                   //date
    int year;       //of input  
    int month;
    int days;
};  
 
Date DateInput();
void DateOut (struct Date );
 
struct bbase
{
    int large;              // large
    int ind;                // id
    char name[100];         // Book's name
    float price;            // Book's price
    char pib[150];          // the author's name
    char kind[50];          // kind of genre
    Date when;           
    int sum;                // count
};
 
 
 
 
int main ()
{   
    check_data ();
 
    do
    {
        int chs; 
        cout<<"\nChoose function:\n"
            <<"1  -  M a k e   f i l e\n"
            <<"2  -  O u t p u t   d a t a\n"
            <<"3  -  D e l e t e   d a t a\n"
            <<"4  -  E d i t   d a t a \n"
            <<"5  -  A d d   d a t a \n"
            <<"6  -  S e a r c h   i n  b a s e\n"
            <<"0  -  E x i t\n"
            <<"Choose: "; 
        chs = inputint ();
        switch (chs)
        {
        case 0: 
            {
                return (0); 
            }
        case 1: 
            {
                Makefile ();cout<<endl; break;
            }
        case 2:
            {
                Readfile();cout<<endl;  break;
            }
        case 3:
            {
                Delefile ();cout<<endl; break;
            }
        case 4:
            {
                Editfile();cout<<endl; break;
            }
        case 5:
            {
                AddData();cout<<endl;break;
            }
        case 6:
            {
                bbSearch();cout<<endl;break;
            }
        default:
            {
                cout<<"Error! Unknown number of function..."; break;
            }
        }
    }
    while (true);
 
 
    return (0);
 
}
 
 
void Makefile ()
{   
    struct bbase dat;
    ofstream f ("base1.txt", ios::out | ios::binary);
    if (!f)
    {
        cout<<" FAIL CANN'T BE OPEN";
    }
    else
    {
        cout<<"Enter size for data: ";
        int lar = inputint();
        f.write((char*)&lar, sizeof(int));
        for (int i=0;i<lar;i++)
        {   
            cout<<i+1<<"-th input \n"; 
            cout<<setw(mark)<<"ID: ";                       dat.ind = inputint();
            cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
            cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
            cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
            cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
            cout<<setw(mark);                               dat.when = DateInput();
            cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
            f.write((char*)&dat, sizeof(struct bbase));
        }
        f.close();  
    }
}
 
//+++++++++++++++++ INPUT      I  N  T
int inputint ()
{    
    int A;
    do
    {
        while(!(cin>>A) || cin.peek() != '\n') 
        {
            cout<<" You did a mistake\n";
            cin.clear(); 
            while (cin.get() != '\n');
            cout<<setw(20)<<"Repit: ";
        }
        if (A < 0)
                cout<<"Input integer >= 0\n";
    } while (A < 0);
    cin.get();
    return A;
}
//+++++++++++++++++++++++++++++++++++++
 
//++++++++++++++input CAHR+++++++++++++
 
void inputchar (char *name, int const size)
{   
    cin.getline(name, size);
}
//++++++++++++++++++++++++++++++++++++++++
 
//+++++++++++++input FLOAT++++++++++++++++
float inputfloat ()
{    float A;
while(!(cin>>A) || cin.get() != '\n') 
{
    cout<<" You did a mistake\n";
    cin.clear(); 
    cin.sync();
    cout<<setw(20)<<"Repit: ";
}
return (A);
}
//+++++++++++++++++++++++++++++++++++++++++
 
void Readfile ()
{
    cout<< "\n\n\tFile contains: \n ";
 
    ifstream f ("base1.txt", ios::in | ios::binary);
    if (!f)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return;
    }
    struct bbase dat;
    int lar;
    f.read((char*)&lar, sizeof(int));
    for (int i=0;i<lar;i++)
    {
        f.read((char*)&dat, sizeof(struct bbase));
        cout<<'\n';
        cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
        cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
        cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
        cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
        cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
        cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
        cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
    }
    f.close();
 
 
}
//+++++++++++++++++++++++++ CHECK 
int check_data ()
{   
    int che = 0;
    fstream f ("base1.txt", ios::in | ios::out);
    if (!f)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return(0);
    }
 
    f.read((char*)&che, sizeof(bool));
    if (che>0) 
    {
        cout<<"Have data in database";
        return (1);
    }
    else
    {
        cout<<"Database is empty...\n"
            <<"You should start with 1-st function\n";
        return (0);
    }
 
}
//+++++++++++++++++++++++++++++++++++   
void Delefile ()
{       
    ofstream f ("base1.txt", ios::out | ios::binary);
    if (!f)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return;
    }
    int lar = 0;
    f.write((char*)&lar, sizeof(bool));
    f.close ();
}
 
//+++++++++++++++ В В О Д   Д А Т Ы +++++++++++++++++
Date DateInput ()
{   
    int C_year;
    int C_month;
    int C_days;
    bool ch_date = false;
    Date shad;
    do
    {
        cout<<"Date of input(YYYY.MM.DD): ";
        cin >> C_year; //год
        cin.ignore();    //точка
        cin >> C_month; //месяц
        cin.ignore();    //точка
        (cin >> C_days).get(); //дата
        if (C_year> 0 && C_month> 0 && C_month<= 12 && C_days > 0 && C_days <= 31)
        {   
            shad.year = C_year;
            shad.month = C_month;
            shad.days = C_days;
            ch_date = true; 
        }
        else 
        {
            cout<<"\nError #2 Probably, you did a mistake in date. Try again!\n";
            ch_date = false;
        }
    }
    while (ch_date != true);
    cout << '\n';
    return (shad);
}
/////////////////////////////////////////////////////////////////
 
////////////////// D A T E    O U T P U T ////////////////////////
void DateOut (Date shad)                                        //
{                                                               //
    cout<<shad.year<<"."<<shad.month<<"."<<shad.days;           //
}                                                               //
//////////////////////////////////////////////////////////////////
 
 
 
void Editfile()
{   
    int n; 
    char chs = 'y'; 
    int count;
    ifstream el ("base1.txt", ios::in | ios::binary);
    if (!el)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter ID: "; n=inputint();
    for (size_t i = 0; i <lar; i++)
    {   
        el.read((char*)&dat,sizeof(struct bbase));
        if (dat.ind == n)
        { 
            cout<<"ID: "<<n<<"\n"; 
            cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
            cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
            cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
            cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
            cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
            cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
            cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
            
            el.close();
            
            cout<<"Do you want change that string? ( y - YES else NO)"; 
            (cin>>chs).get();
            if (chs == 'y')
            {
                char chs2;
                cout<<" Do you want to change wholly statement? ( y - YES else NO)";
                (cin>>chs2).get();
                ////////////////////////////////////////////////////////////////////////////
                //      if (chs2 == 'y')
                {
                    fstream er ("base1.txt", ios::in | ios::out | ios::binary); 
                    if (!er)
                    {
                        cout<<" FAIL CANN'T BE OPEN"; return;
                    }   
                    struct bbase dat2;
                    cout<<"ID: "<<n<<"\n"; 
                    cout<<setw(mark)<<"ID: ";                       dat2.ind =inputint();
                    cout<<setw(mark)<<"Book's name: ";              cin.getline(dat2.name, 100);
                    cout<<setw(mark)<<"Price: ";                    dat2.price = inputfloat ();
                    cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat2.pib, 150);
                    cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat2.kind, 50);
                    cout<<setw(mark);                               dat2.when = DateInput();
                    cout<<setw(mark)<<"Amount: ";                   dat2.sum = inputint();
                    er.seekp (sizeof (int)+(sizeof(struct bbase)*i), ios::beg);
                    er.write((char*)&dat2,sizeof(struct bbase));
                    er.close();
                    return;
                }
                /*  else
                {   
                fstream el ("base1.txt", ios::in | ios::out | ios::binary); 
                if (!el)
                {
                cout<<" FAIL CANN'T BE OPEN"; return;
                }
 
                int X;
                cout<<"Enter number of line: ";
                cin>>X;
                switch (X)
                {
                case 1:
                {
                cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
                break;
                }
                case 2:
                {
                cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
                break;
                }
                case 3:
                {
                cout<<setw(mark)<<"Price: ";                    dat.price = inputfloat ();
                break;
                }
                case 4:
                {
                cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
                break;
                }
                case 5:
                {
                cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
                break;
                }
                case 6:
                {
                cout<<setw(mark);                               dat.when = DateInput();
                break;
                }
                case 7:
                {
                cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
                break;
                }
                default:
                {
                cout<<"Wrong number of line\n";
                break;
                }
 
                }   // end of switch (X)
                el.seekp (sizeof(bool)+ sizeof (int)+sizeof (struct bbase)*(i), ios::beg);
                el.write((char*)&dat,sizeof(struct bbase));
                el.close();
                return; 
                }   // end of else
                */
            }   // Wholly statment or not
 
 
        } //  I F ()
    } // FOR 
    cout<< "\n Unknown ID...";
}
 
void AddData ()
{   
    int n=0; 
    int lar;
    cout<<"How much do you want to add?"<<endl;
    cout<<"Size: "; 
    n=inputint ();
    fstream la ("base1.txt", ios::in | ios::out);
    if (!la)
        cout<<" FAIL CANN'T BE OPEN\n";
    else 
        la.read((char*)&lar,sizeof(int));
 
    lar+=n; 
    la.seekp(ios::beg);
    la.write((char*)&lar, sizeof (int));
    la.close();
    ofstream  em ("base1.txt", ios::app); 
    if (!em)
    {
        cout<<" FAIL CANN'T BE OPEN"; return;
    }
    for (size_t i = 0; i<n; i++)
    {
        struct bbase dat; 
        cout<<setw(mark)<<"ID: ";                       dat.ind =inputint();
        cout<<setw(mark)<<"Book's name: ";              cin.getline(dat.name, 100);
        cout<<setw(mark)<<"Price: ";                    dat.price = inputint();
        cout<<setw(mark)<<"The autor's name: ";         cin.getline(dat.pib, 150);
        cout<<setw(mark)<<"Kind of genre: ";            cin.getline(dat.kind, 50);
        cout<<setw(mark);                               dat.when = DateInput();
        cout<<setw(mark)<<"Amount: ";                   dat.sum = inputint();
        em.write((char*)&dat,sizeof (struct bbase)); 
    }
    em.close();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////SEARCH SECTOR///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void bbSearch  ()
{   
    int ch;
    cout<<"Whar do you want to search? \n"
        <<"1 - In pursuant Price \n"
        <<"2 - Autors, genre, book's naem\n"
        <<"3 - In pursuant amount range\n"
        <<"0 - EXIT\n";
    (cin>> ch).get();
    switch (ch)
    {
    case 1:
        {
            seaPrice ();break;
        }
    case 2:
        {
            seaString ();break;
        }
    case 3:
        {
            seaRange(); break;
        }
    case 0: return;
 
    default:{cout<<"Unkown funcion..."; break;}
    }
}
 
void seaPrice ()
{   
    int range;
    int n=0;
    ifstream el ("base1.txt", ios::in | ios::binary);
    if (!el)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return;
    }
    int lar;
    struct bbase dat;
    el.read((char*)&lar, sizeof(int));
    cout<<"Enter Price: "; n=inputint();
    cout<<"1 - cheaper then '"<<n<<"', 2 - more \n"; 
    (cin>>range).get(); 
    switch (range)
    {
    case 1:
        {
            for (size_t i = 0; i <lar; i++)
            {       
                el.read((char*)&dat, sizeof(struct bbase));
                if (dat.price <= n)
                {cout<<endl;
                cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
                cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
                cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
                cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
                cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
                cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
                cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
                }       
            }
            break;}// case 1
 
    case 2:
        {
            for (size_t i = 0; i <lar; i++)
            {       
                el.read((char*)&dat, sizeof(struct bbase));
                if (dat.price >= n)
                {cout<<endl;
                cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
                cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
                cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
                cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
                cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
                cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
                cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
                }       
            }
            break;} // case 2
    default: {cout<<"Unknown function...\n";break;}
    }// end of switch
    el.close();
} // end of seaPrice()  
 
void seaString ()
{   
    int lar;
    int ch;
 
    ifstream el ("base1.txt", ios::in | ios::binary);
    if (!el)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return;
    }
 
    el.read((char*)&lar, sizeof (int));
 
    cout<<" Enter function: \n";
    cout<<" 1 - Search books  in order autor\n"
        <<" 2 - Search books in ordet genre\n"
        <<" 3 - Search book's name\n"
        <<" 0 - EXIT\n";
    (cin>>ch).get();
    switch (ch)
    {
    case 1: 
        {   
            char spib[150];
 
            cout<<"Enter Autor's name: ";
            //cin.ignore();
            cin.getline(spib, 150);
            for (unsigned short int i = 0; i<lar; i++ )
            {   
                struct bbase dat;
                el.read((char*)&dat,sizeof (bbase));
                if (stricmp(spib,dat.pib) == 0)
                {
                    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
                    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
                    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
                    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
                    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
                    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
                    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
                }
            }
            break;} // end of case 1 for autors name
    case 2:
        {
            char skind[50];
            cout<<"Enter genre: "; 
            //cin.ignore();
            cin.getline(skind,50);
            for (unsigned short int i = 0; i<lar; i++ )
            {   
                struct bbase dat;
                el.read((char*)&dat,sizeof (bbase));
                if (stricmp(skind,dat.kind) == 0)
                {
                    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
                    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
                    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
                    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
                    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
                    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
                    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
                }
            }// for
            break;} // end of case 2 for kind
    case 3: 
        {
            char sname[100];
            cout<<"Enter book's name: "; 
            //cin.ignore();
            cin.getline(sname,100);
            for (unsigned short int i = 0; i<lar; i++ )
            {   
                struct bbase dat;
                el.read((char*)&dat,sizeof (bbase));
                if (stricmp(sname,dat.name) == 0)
                {
                    cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
                    cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
                    cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
                    cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
                    cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
                    cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
                    cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
                }
            }// for 
        }
    case 0:
        {   el.close ();
        return; 
        }
    default:{cout<<"Unknown function...";break;}
    }       // end of switch
    el.close ();
}
 
void seaRange ()
{   
    unsigned a =0; unsigned b= 0;
    cout<<"Enter range for amount, for example (1-100)\n"
        <<"__"; 
    cout<<setw(4);
    (cin>>a).get();
    //cin.ignore();
    cout<<setw(4);
    (cin>>b).get();
    ifstream el ("base1.txt", ios::in | ios::binary);
    if (!el)
    {
        cout<<" FAIL CANN'T BE OPEN";
        return;
    }
    int lar;
 
    el.read((char*)&lar, sizeof(int));
    for (unsigned i = 0; i<lar; i++)
    {   struct bbase dat;
    el.read((char*)&dat, sizeof(bbase));
    if (dat.sum>= a && dat.sum<=b)
    {
        cout<<setw(mark)<<"ID: ";                           cout<<dat.ind<<endl;
        cout<<setw(mark)<<"Book's name: ";                  cout<<dat.name<<endl;
        cout<<setw(mark)<<"Price: ";                        cout<<dat.price<<endl;
        cout<<setw(mark)<<"The autor's name: ";             cout<<dat.pib<<endl;
        cout<<setw(mark)<<"Kind of genre: ";                cout<<dat.kind<<endl;
        cout<<setw(mark)<<"Date of input(YYYY.MM.DD): ";    DateOut(dat.when);cout<<endl;
        cout<<setw(mark)<<"Amount: ";                       cout<<dat.sum<<endl;
    }
    }
 
}
1
1 / 1 / 0
Регистрация: 28.02.2013
Сообщений: 62
01.02.2014, 16:24  [ТС] 19
Цитата Сообщение от alsav22 Посмотреть сообщение
Вот и нужно было выяснить - почему? Если делаете, как нужно, и код перестаёт работать, значит код кривой.
Был бы он "прямой" я бы сюда не обратился.
Цитата Сообщение от alsav22 Посмотреть сообщение
Вот ваш код, в котором, во всех случаях открытия файла, это делается в бинарном режиме. И почему-то нормально работает:
Я Вам скажу больше: на другой машине все работало нормально и без вмешательств в исходный код. Почему? Я сам не знаю, но когда стал вопрос переноса на другую, то выплыли все косяки и именно в этот момент родилась эта тема. Безусловно Ваша игра в загадки мне ну ооочень понравилась, но ведь можно же было сократить путь до 3-х строчного сообщения в 1-м посту.
Например:
Цитата Сообщение от example
В вашем случае, при записи c помощью произвольного доступа, рекомендуется использовать бинарный режим (изучите ios::binary). Изменения стоит внести на стадии открытия файла. В противном случае, при перекодирование записанной информации в файл, будет сопровождаться непредсказуемыми последствиями, например: записывает, выводит, читает мусор.
Не смотрят ни на что: Спасибо за потраченное на меня, такого непутёвого, своего личного времени и сил!
0
alsav22
01.02.2014, 19:06     В файл записывается мусор. Подкорректировать код
  #20

Не по теме:

Цитата Сообщение от GraBLYA Посмотреть сообщение
Безусловно Ваша игра в загадки мне ну ооочень понравилась
О каких загадках речь? Элементарные вещи тут никто разжёвывать не будет. Для этого есть учебники, в которые вас, буквально, носом тыкали:
Цитата Сообщение от alsav22 Посмотреть сообщение
Если с Дейтлом, то читайте, в главе 17: "Произвольная запись данных в файл произвольного доступа".
Цитата Сообщение от GraBLYA Посмотреть сообщение
но ведь можно же было сократить путь до 3-х строчного сообщения в 1-м посту.
Например: "В вашем случае, при записи c помощью произвольного доступа, рекомендуется использовать бинарный режим (изучите ios::binary). Изменения стоит внести на стадии открытия файла. В противном случае, при перекодирование записанной информации в файл, будет сопровождаться непредсказуемыми последствиями, например: записывает, выводит, читает мусор."
Смотрим мой первый пост (в одну строчку):
Цитата Сообщение от alsav22 Посмотреть сообщение
Для начала... Файлы пишите/читаете бинарными методами, а открываете файлы в текстовом режиме.
Кому и что непонятно? Не только разжевать, но ещё и в рот положить?

0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
01.02.2014, 19:06

В массив почему-то записывается мусор
Здравствуйте, дело вот в чем, пишу курсовую программу. Когда рассчитываю массив (тип float) в цикле...

После выхода из функции в переменные записывается мусор
//Class1.h class Class2; class Class1 { public: double a1; char *a2; char *a3; ...

подкорректировать код С++
#include&lt;iostream&gt; #include&lt;fstream&gt; #include&lt;string&gt; #include&lt;vector&gt; using namespace std; ...

Подкорректировать код
Здравствуйте, уважаемые программисты. Подскажите, пожалуйста, решение: Исправьте ошибки в...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru