Форум программистов, компьютерный форум CyberForum.ru

Ошибка при компиляции error LNK2019 - C++

Восстановить пароль Регистрация
Другие темы раздела
C++ Разработать программу «Вычислитель площадей» http://www.cyberforum.ru/cpp-beginners/thread816359.html
помогите прошу Разработать программу «Вычислитель площадей», позволяющую вычислять площадь плоских геометрических фигур
C++ Разработать программу «Вычислитель площадей» помогите пожалуйста Разработать программу «Вычислитель площадей», позволяющую вычислять площадь плоских геометрических фигур http://www.cyberforum.ru/cpp-beginners/thread816358.html
C++ Числа Грея
Нужно написать программу, которая читает два числа и выводит являются они соседними по коду Грея или нет. Никаких идей как реализовать... Нашел только код Грея... #include <iostream> using namespace std; int main() { int codeGray, k, m; cout<<"Input 2 numbers:"<<endl;
C++ Создание библиотеки
Имеются проекты.. Как из них сделать библиотеки и подключить к своей программе? В инете что находил - не прокатывало, т.к. там написано как создавать библиотеки с 0, а не уже с имеющегося проекта...
C++ двухсвязный список http://www.cyberforum.ru/cpp-beginners/thread816339.html
#include "stdafx.h" #include <iostream> #include <locale.h> #include <string> using namespace std; struct List { List *next;
C++ альтренатива С++ BeeLisp Хочу начать изучать С++, монжо ли с билиспа начать? На сайте там пишут вроде похож на него. И по проще. подробнее

Показать сообщение отдельно
DarkPower
0 / 0 / 0
Регистрация: 20.03.2013
Сообщений: 79
23.03.2013, 17:19  [ТС]     Ошибка при компиляции error LNK2019
Цитата Сообщение от Kuzia domovenok Посмотреть сообщение
выкладывай текст тут, иначе никто качать не будет.
Можно только догадываться: В проекте не хватает исходника или библиотеки с функцией GTASA_CRC32_fromUpCaseString
Всё есть... И всё вроде подключенно...

Голова:
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
// VFansss.cpp : Defines the entry point for the console application.
 
//
 
#include "stdafx.h"
#include "IMG.h"
char* FileInMemory = NULL;
 
unsigned int FileSize;
 
// Loads file into memory
 
void LoadFileIntoMemory(char* filename)
 
{
 
        if(FileInMemory)  delete FileInMemory;
 
        if(FILE* fp = fopen(filename, "rb"))
        {
 
                fseek(fp, 0, SEEK_END);
                FileSize = ftell(fp);
                FileInMemory = new char[FileSize];
                fseek(fp, 0, SEEK_SET);
                fread(FileInMemory, 1, FileSize, fp);
                fclose(fp);
        }
}
 
 
int _tmain(int argc, _TCHAR* argv[])
 
{
 
        IMG archive;
 
        archive.OpenArchive("gta3.img");
 
        LoadFileIntoMemory("TEST.TXT");
 
        archive.AddOrReplaceFile("TEST.TXT", FileInMemory, FileSize);
 
        LoadFileIntoMemory("TEST2.TXT");
 
        archive.AddOrReplaceFile("TEST2.TXT", FileInMemory, FileSize);
 
        delete FileInMemory;
 
        archive.CloseArchive();
 
        getchar();
 
        return 0;
 
}
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
#include "IMG.h"
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** IMG.cpp
** Class to create or edit GTA IMG archives with efficient algorithms.
** Works wth archive versions:
** • version 1 (GTA III, GTA VC, GTA III Mobile)
** • version 2 (GTA SA)
** does not support GTA IV yet.
**
** Version: 1.5
** Author: fastman92
** Site: fastman92-site.tk
** -------------------------------------------------------------------------*/
 
#include <windows.h>
#include <vector>
#include <algorithm>
#include <io.h>
#include <iostream>
#include "Shlwapi.h"
#pragma comment( lib, "shlwapi.lib")
 
#include "GTASA_CRC32.h"
// #include "Rijndael.h"
 
#define GET_ALIGNED_SIZE(requested_size, block_size) (requested_size % block_size == 0 ? requested_size : ((requested_size / block_size)+1)*block_size)
#define GET_ALIGNED_SIZE_IN_BLOCKS(requested_size, block_size) (requested_size % block_size == 0 ? requested_size / block_size : (requested_size / block_size) + 1)
 
// #define IMG_DEBUG
 
class IMG
{
public: 
    enum ResourceTypes : DWORD
    {
        RESOURCE_UNDEFINED = 0x00,
        RESOURCE_GENERIC = 0x01,
        RESOURCE_TEXTURE_ARCHIVE = 0x08,
        RESOURCE_BOUNDS = 0x20,
        RESOURCE_MODEL_FILE = 0x6E,
        RESOURCE_XPFL = 0x24
    };
 
    class IMG_Entry
    {
        friend IMG;
 
    private:
        char Name[256];             // NULL terminated
        DWORD NameHash;
 
        // In IMG archive
        DWORD Position;             // In blocks
        WORD SizeSecondPriority;    // In blocks
        WORD SizeFirstPriority;     // In blocks
 
        // Version 3
        DWORD SizeInBytes;
        // DWORD SizeInBlocks;
        ResourceTypes ResourceType;
 
        // Updates hash of file name 
        void IMG::IMG_Entry::UpdateFileNameHash();
 
        // Get file size aligned blocks
        size_t IMG::IMG_Entry::GetFilesizeAllignedToBlocks();
 
    public: 
        IMG* IMG_Instance;
 
        // For reading/writing
        unsigned int curPos;
 
        /////// Methods
 
        // Constructor
        IMG::IMG_Entry::IMG_Entry(IMG * IMG_Instance);
 
        // Returns pointer to file name.
        const char* IMG::IMG_Entry::GetFilename();
 
        // Reads whole file, doesn't affect current file position (curPos)
        // Returns number of bytes read.
        size_t IMG::IMG_Entry::ReadEntireFile(void* ptr);
 
        // Get file size in bytes
        size_t IMG::IMG_Entry::GetFilesize();
 
        //////// File operations that may affect curPos
        // Reads to memory
        size_t IMG::IMG_Entry::Read(void* Ptr, size_t Size);
 
        // Reads one byte
        char IMG::IMG_Entry::ReadC();
 
        // Write data
        size_t IMG::IMG_Entry::Write(void* ptr, size_t size);
 
        // Check End-of-File indicator
        bool IMG::IMG_Entry::isEOF();
 
        // Seek to certain position
        bool IMG::IMG_Entry::Seek(unsigned int offset, int origin);
 
        // Returns current position
        unsigned int IMG::IMG_Entry::Tell();
    };
 
private:
#ifdef IMG_DEBUG
    FILE* debugFile;
#endif
 
    // File entries
    std::vector <IMG_Entry> ListOfEntries;
 
    FILE* IMG_Handle;
    FILE* DIR_Handle;
 
    char IMG_fullPath [MAX_PATH];
    char* IMG_filename;
 
    // Size of all filenames, only usabe, when IMG version 3
    DWORD FilenamesSize;
 
    // Get end of list entries and header
    DWORD IMG::GetEndOfHeaderDataPastTheListOfFiles();
 
    // Moves files located in position before list of files to suitable position
    void IMG::MoveFilesLocatedBeforeListOfFilesToSuitablePosition(FILE* imgHandle);
 
    // Returns pattern of IMG validity
    void IMG::GetPatternToCheckIfPositionIsValid(char* str);
 
    // Tests if file position is valid
    void IMG::TestIfPositionIsValid(FILE* imgHandle);
 
    // reads version 1 or 2 header
    void IMG::ReadEntryOfVersion1And2Header(IMG_Entry& entry, FILE* file);
 
    // writes version 1 or 2 header
    void IMG::WriteListOfEntriesVersion1And2(FILE* file);
    
    // Updates list of entries in IMG archive/DIR file
    void IMG::WriteListOfEntries(FILE* imgHandle = NULL);
 
    // Writes file content alligned to IMG_BLOCK_SIZE
    // Returned value is number of blocks written ( realSize / IMG_BLOCK_SIZE )
    size_t IMG::WriteAllignedFileToIMGblocks(const void* ptr, size_t size);
 
    // Sorts an array by
    // 1. Position
    // 2. Size
    void IMG::SortListOfEntriesByPositionAndSize(std::vector<IMG_Entry>& list);
 
    // Finds a first free space for target file
    unsigned __int64 IMG::FindFirstEmptySpaceForFile(size_t filesize, DWORD overwrittenFileIndex = UNDEFINED);
 
public:
    const static unsigned int IMG_BLOCK_SIZE = 2048;        // 2 KB
    const static unsigned int UNDEFINED = 0xFFFFFFFF;
    const static unsigned int MAX_FILESIZE = 0xFFFF * IMG_BLOCK_SIZE;       // 128 MB - IMG_BLOCK_SIZE bytes
    const static unsigned int GTAIV_MAGIC_ID = 0xA94E2A52;
 
    char* GTAIV_encryption_key;
 
    #pragma pack(push, 1)
    struct IMG_version2_tableItem       // size: 20 bytes
    {
        DWORD Position;             // In blocks
        WORD SizeSecondPriority;    // In blocks
        WORD SizeFirstPriority;     // In blocks
        char Name[24];              // NULL terminated
    };
    #pragma pack(push, 1)
 
    #pragma pack(push, 1)
    struct IMG_version3_header      // size: 20 bytes
    {
        DWORD MagicID;
        DWORD Version;              // always should be 3
        DWORD NumberOfItems;
        DWORD TableOfItemsSize;
        WORD SingleTableItemSize;   // should be 0x10 (16)
        WORD Unknown;
    };
    #pragma pack(push, 1)
 
    struct IMG_version3_tableItem       // size: 20 bytes
    {
        DWORD SizeInBytes;
        ResourceTypes ResourceType;
        DWORD Position;     // in blocks
        WORD SizeInBlocks;
        WORD Unknown;
    };
 
    enum IMG_version
    {
        IMG_VERSION_UNDEFINED,
        IMG_VERSION_1,  // GTA III, GTA VC, GTA III Mobile
        IMG_VERSION_2,  // GTA SA
        IMG_VERSION_3_UNENCRYPTED,  // GTA IV
        IMG_VERSION_3_ENCRYPTED     // GTA IV
    };
 
    IMG_version archiveVersion;
 
private:
    // Writes IMG archive version 3 header to memory.
    void IMG::WriteVersion3HeaderToMemory(IMG_version3_header* header);
 
public:
 
    // Default constructor
    IMG::IMG();
 
    // Destructor
    IMG::~IMG();
 
    // Copy constructor
    // IMG::IMG(const IMG &cSource);
 
    // Opens IMG archive, assumes IMG archive to exist.
    // Detects archive type automatically
    bool IMG::OpenArchive(const char* path);
 
    // Creates .img archive
    // Example: object.CreateArchive("new.img", IMG::IMG_version::VERSION_1);
    bool IMG::CreateArchive(const char* path, IMG_version version);
 
    // Opens .img archive if exists or creates if not exists
    // Example: object.OpenOrCreateArchive("new.img", IMG::IMG_version::VERSION_1);
    bool IMG::OpenOrCreateArchive(const char* path, IMG_version version);
 
    // Checks if archive is currently opened.
    bool IMG::IsArchiveOpened();
 
    // Closes archive
    void IMG::CloseArchive();
 
    // Rebuilds archive
    bool IMG::RebuildArchive();
 
    // Gets the size of .img archive in bytes
    unsigned __int64 IMG::GetImgArchiveSize();
 
    // Gets size of unused space in .img file
    unsigned __int64 IMG::GetSizeOfUnusedSpace();
    
    // Retrieves the number of files inside of IMG archive
    DWORD IMG::GetFileCount();
 
    // Adds or replaces file if exists
    void IMG::AddOrReplaceFile(const char* name, const void* ptr, size_t size);
 
    // Adds file
    void IMG::AddFile(const char* name, const void* ptr, size_t size);
 
    // Replaces file depending on index
    void IMG::ReplaceSingleFile(DWORD index, const void* ptr, size_t size);
 
    // Renames a file
    void IMG::RenameFile(DWORD index, const char* NewName);
 
    // Removes a file
    void IMG::RemoveFile(DWORD index);
 
    // Removes files
    void IMG::RemoveFiles(DWORD start, DWORD end);
 
    // Remove a file
    std::vector<IMG::IMG_Entry>::iterator IMG::RemoveFile(std::vector<IMG::IMG_Entry>::const_iterator _Where);
 
    // Removes files
    std::vector<IMG::IMG_Entry>::iterator IMG::RemoveFiles(
        std::vector<IMG::IMG_Entry>::const_iterator _First_arg,
        std::vector<IMG::IMG_Entry>::const_iterator _Last_arg
        );
 
    // Gets index of file pointing to ListOfFiles
    unsigned int IMG::GetFileIndexByName(const char* name);
 
    // Checks if file with specified name exists and returns TRUE/FALSE
    bool IMG::FileExists(const char* name);
 
    // Gets filename for imported file, filename may be truncated if archive version is 1 or 2.
    errno_t IMG::GetFilenameForImportedFile(const char* lpFileName, char* lpFilePart, DWORD nBufferLength);
 
    // Access element
    // Returns a reference to the file at position n in the vector.
    std::vector<IMG::IMG_Entry>::reference IMG::at(std::vector<IMG::IMG_Entry>::size_type n);
 
    // Access element
    // Returns a reference to the file at position n in the vector.
    std::vector<IMG::IMG_Entry>::const_reference IMG::at(std::vector<IMG::IMG_Entry>::size_type n) const;
 
    // Access file by name
    // Returns a reference to the last element in the vector container.
    std::vector<IMG::IMG_Entry>::reference IMG::GetFileRefByName(const char* name);
    
    // Return iterator to beginning
    std::vector<IMG::IMG_Entry>::iterator IMG::begin();
 
    // Return iterator to beginning
    std::vector<IMG::IMG_Entry>::const_iterator IMG::begin() const;
 
    // Return iterator to end
    std::vector<IMG::IMG_Entry>::iterator IMG::end();
 
    // Return iterator to end
    std::vector<IMG::IMG_Entry>::const_iterator IMG::end() const;
 
    // Return reverse iterator to reverse beginning
    std::vector<IMG::IMG_Entry>::reverse_iterator IMG::rbegin();
 
    // Return reverse iterator to reverse beginning
    std::vector<IMG::IMG_Entry>::const_reverse_iterator IMG::rbegin() const;
 
    // Return reverse iterator to reverse end
    std::vector<IMG::IMG_Entry>::reverse_iterator IMG::rend();
 
    // Return reverse iterator to reverse end
    std::vector<IMG::IMG_Entry>::const_reverse_iterator IMG::rend() const;
 
    // Access last element
    // Returns a reference to the last element in the vector container.
    std::vector<IMG::IMG_Entry>::reference IMG::back();
 
    // Access last element
    // Returns a reference to the last element in the vector container.
    std::vector<IMG::IMG_Entry>::const_reference IMG::back() const;
 
    // Access first element
    // Returns a reference to the first element in the vector container.
    std::vector<IMG::IMG_Entry>::reference IMG::front();
 
    // Access first element
    // Returns a reference to the first element in the vector container.
    std::vector<IMG::IMG_Entry>::const_reference IMG::front() const;
 
    // Outputs list of entries specified as argument
    void IMG::DebugListOfEntries(std::vector<IMG_Entry>& list);
 
    // Outputs ListOfEntries
    void IMG::DebugListOfEntries();
};
#include "GTASA_CRC32.h"

C++
1
2
3
4
5
#include <ctype.h>
 
unsigned long GTASA_CRC32_fromString(const char* string);
 
unsigned long GTASA_CRC32_fromUpCaseString(const char* string);
IMG.CPP
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** IMG.cpp
** Class to create or edit GTA IMG archives with efficient algorithms.
** Works wth archive versions:
** • version 1 (GTA III, GTA VC, GTA III Mobile)
** • version 2 (GTA SA)
** does not support GTA IV yet.
**
** Version: 1.5
** Author: fastman92
** Site: fastman92-site.tk
** -------------------------------------------------------------------------*/
 
#include "stdafx.h"
#include "IMG.h"
 
using namespace std;
 
int fileChangeSize(FILE *fp, __int64 size)
{ 
    __int64 position = _ftelli64(fp);
    fseek(fp, 0, SEEK_SET);
 
    int filedes = _fileno(fp); 
    int result =_chsize_s(filedes, size);
 
    if(position < size)
        _fseeki64(fp, position, SEEK_SET);
 
    return result;
}
 
// Default constructor
IMG::IMG()
{
#ifdef IMG_DEBUG
    this -> debugFile = fopen("IMG_debug.log", "w");
    
    if(debugFile)
    {
        const char text[] = "IMG object initialized\n";
        fwrite(text, sizeof(text)-1, 1, debugFile);
    }
#endif
 
    this -> IMG_Handle = NULL;
    this -> DIR_Handle = NULL;
    this -> archiveVersion = IMG_VERSION_UNDEFINED;
 
    this -> GTAIV_encryption_key = "\x1a\xb5\x6f\xed\x7e\xc3\xff\x1\x22\x7b\x69\x15\x33\x97\x5d\xce"
        "\x47\xd7\x69\x65\x3f\xf7\x75\x42\x6a\x96\xcd\x6d\x53\x7\x56\x5d";
 
    this -> FilenamesSize = 0;
}
 
// Destructor
IMG::~IMG()
{
#ifdef IMG_DEBUG
    fclose(this -> debugFile);
#endif
 
    this -> CloseArchive();
}
 
// Opens IMG archive, assumes IMG archive to exist.
// Detects archive type automatically
bool IMG::OpenArchive(const char* path)
{
    this -> CloseArchive();
 
    if(this -> IMG_Handle = fopen(path, "rb+"))
    {       
        GetFullPathNameA(path, _countof(this -> IMG_fullPath), this -> IMG_fullPath, &this -> IMG_filename);
 
        unsigned long int version;
 
        size_t NumberOfReadBytes = fread(&version, sizeof(char), 4, this -> IMG_Handle);
 
        if(NumberOfReadBytes == 4 && version == '2REV')
        {
            this -> archiveVersion = IMG_VERSION_2;
 
            unsigned long int n_files;
 
            fread(&n_files, 1, 4, this -> IMG_Handle);
 
            while(n_files > 0)
            {
                if(feof(this -> IMG_Handle))
                {
                    this -> CloseArchive();
                    return false;
                }
                this -> ListOfEntries.push_back(IMG_Entry(this));
                this -> ReadEntryOfVersion1And2Header(ListOfEntries.back(), this -> IMG_Handle);
                n_files--;
            }
 
            return true;
        }
        else
        {
            const char* extension = strrchr(path, '.');
            
            bool hasExtension = false;
 
            char dirPath[_MAX_PATH];
 
            if(extension)
            {
                extension++;
                hasExtension = true;
                
                memcpy(dirPath, path, extension - path);
                strcpy(&dirPath[extension - path], "dir");
            }
                    
            if(hasExtension && (this -> DIR_Handle = fopen(dirPath, "rb+")))
            {
                fseek(this -> DIR_Handle, 0, SEEK_END);                 
 
                size_t DIR_size = ftell(this -> DIR_Handle);
 
                    if(DIR_size % 32 == 0)
                    {
                        fseek(this -> DIR_Handle, 0, SEEK_SET);
                         
                        this -> archiveVersion = IMG_VERSION_1;
                                                                
                        for(unsigned int i = 0; i < DIR_size / 32; i++)
                        {
                            this -> ListOfEntries.push_back(IMG_Entry(this));
                            this -> ReadEntryOfVersion1And2Header(ListOfEntries.back(), this -> DIR_Handle);
                        }
                                
                        return true;
                    }
            }
            else if(NumberOfReadBytes == 4)
            {
                if(version == GTAIV_MAGIC_ID)
                    this -> archiveVersion = IMG_VERSION_3_UNENCRYPTED;
                else
                    this -> archiveVersion = IMG_VERSION_3_ENCRYPTED;
 
                IMG_version3_header Header;
 
                if(fread(&Header.Version, 1, sizeof(Header) - 4, this -> IMG_Handle) == sizeof(Header) - 4 && Header.Version == 3
                    && Header.SingleTableItemSize == 16)
                {                   
                    for(unsigned int FileNum = 0; FileNum < Header.NumberOfItems; FileNum++)
                    {
                        IMG_version3_tableItem item;
                        if(fread(&item, sizeof(IMG_version3_tableItem), 1, this -> IMG_Handle) != 1)
                            goto closeArchiveAndReturnFalse;
 
                        this -> ListOfEntries.push_back(IMG_Entry(this));
                        auto& CurrentEntry = this -> ListOfEntries.back();
                        CurrentEntry.Position = item.Position;
                        CurrentEntry.SizeInBytes = item.SizeInBytes;
 
                        DWORD SizeInBlocks = GET_ALIGNED_SIZE_IN_BLOCKS(item.SizeInBytes, IMG_BLOCK_SIZE);
 
                        if(SizeInBlocks > item.SizeInBlocks)
                        {
                            cout << hex << item.SizeInBytes;
                            goto closeArchiveAndReturnFalse;
                        }
 
                        CurrentEntry.ResourceType = (ResourceTypes)item.ResourceType;
                    }                   
 
                    this -> FilenamesSize = Header.TableOfItemsSize - (Header.NumberOfItems * Header.SingleTableItemSize);
                    char* Filenames = new char[FilenamesSize];
 
                    if(fread(Filenames, FilenamesSize, 1, this -> IMG_Handle) != 1)
                    {
                        delete Filenames;
                        return false;
                    }
 
                    char* CurrentFilename = Filenames;
                    for(auto& entry = this -> ListOfEntries.begin(); entry < this -> ListOfEntries.end(); entry++)
                    {   
                        unsigned int i;
 
                        for(i = 0; CurrentFilename[i]; i++)
                            entry -> Name[i] = CurrentFilename[i];
 
                        entry -> Name[i] = NULL;
 
                        entry -> UpdateFileNameHash();
 
                        CurrentFilename += i + 1;
                    }
 
                    delete Filenames;
 
                    return true;
                }               
            }
        }
 
        closeArchiveAndReturnFalse:
        this -> CloseArchive();
        return false;
    }
    else
        return false;
}
 
// Creates .img archive
// Example: object.CreateArchive("new.img", IMG::IMG_version::VERSION_1);
bool IMG::CreateArchive(const char* path, IMG_version version)
{
    this -> CloseArchive();
    
    GetFullPathNameA(path, _countof(this -> IMG_fullPath), this -> IMG_fullPath, &this -> IMG_filename);
 
    this -> archiveVersion = version;
 
    switch(version)
    {
    case IMG_VERSION_1: 
        {
            const char* extension;
            
                if((extension = strrchr(path, '.'))++)
                {
                    char dirPath[_MAX_PATH];
                    memcpy(dirPath, path, extension - path);
                    strcpy(&dirPath[extension - path], "dir");
 
                    if((this -> DIR_Handle = fopen(dirPath, "wb+")) && (this -> IMG_Handle = fopen(path, "wb+")))
                    {
                        this -> WriteListOfEntries();
                        return true;
                    }
                    else
                        this -> CloseArchive();
                }               
            return false;
        }
    case IMG_VERSION_2:     
        {
            if(this -> IMG_Handle = fopen(path, "wb+"))
            {
                fwrite("VER2\x0\x0\x0\x0", 1, 8, this -> IMG_Handle);
 
                this -> WriteListOfEntries();
                return true;
            }
            return false;
        }
    case IMG_VERSION_3_UNENCRYPTED:
    case IMG_VERSION_3_ENCRYPTED:
        {
            if(this -> IMG_Handle = fopen(path, "wb+"))
            {
                this -> WriteListOfEntries();
                return true;
            }
 
            return false;
        }
 
    default:
        this -> archiveVersion = IMG_VERSION_UNDEFINED;
        return false;
    }
}
 
// Opens .img archive if exists or creates if not exists
// Example: object.OpenOrCreateArchive("new.img", IMG::IMG_version::VERSION_1);
bool IMG::OpenOrCreateArchive(const char* path, IMG_version version)
{
    if(PathFileExistsA(path))
        return this -> OpenArchive(path);
    else
        return this -> CreateArchive(path, version);
}
 
// Checks if archive is currently opened.
bool IMG::IsArchiveOpened()
{
    return this -> IMG_Handle != false;
}
 
// Closes archive
void IMG::CloseArchive()
{
    this -> ListOfEntries.clear();
 
    if(this -> IMG_Handle)
    {
        fclose(this -> IMG_Handle);
        this -> IMG_Handle = NULL;
    }
    if(this -> DIR_Handle)
    {
        fclose(this -> DIR_Handle);
        this -> DIR_Handle = NULL;
    }
}
 
// Rebuilds archive
bool IMG::RebuildArchive()
{
    char temporaryImgFilepath[_countof(this -> IMG_fullPath) + 16];
    strcpy(temporaryImgFilepath, this -> IMG_fullPath);
    strcat(temporaryImgFilepath, ".IMGclassTmpFile");
 
    FILE* newIMGhandle;
    
    if(newIMGhandle = fopen(temporaryImgFilepath, "wb+"))
    {
        if(this -> archiveVersion == IMG_VERSION_2)
            fwrite("VER2\x0\x0\x0\x0", 1, 8, newIMGhandle);
 
        fseek(newIMGhandle, GET_ALIGNED_SIZE(GetEndOfHeaderDataPastTheListOfFiles(), IMG_BLOCK_SIZE), SEEK_SET);
 
        for(auto entry = ListOfEntries.begin(); entry < ListOfEntries.end(); entry++)
        {
            size_t size = entry -> GetFilesizeAllignedToBlocks();
            char* loadedFile = new char[size];
            
            _fseeki64(this -> IMG_Handle, (unsigned __int64) entry ->Position * IMG_BLOCK_SIZE, SEEK_SET);
            fread(loadedFile, 1, size, this -> IMG_Handle);         
 
            entry -> Position =(DWORD) (_ftelli64(newIMGhandle) / IMG_BLOCK_SIZE);
            fwrite(loadedFile, 1, size, newIMGhandle);
    
            delete loadedFile;          
        }
 
        this -> WriteListOfEntries(newIMGhandle);
 
        fclose(newIMGhandle);
        fclose(this -> IMG_Handle);     
 
        remove(this -> IMG_fullPath);
        rename(temporaryImgFilepath, this -> IMG_fullPath);
 
        return (this -> IMG_Handle = this -> IMG_Handle = fopen(this -> IMG_fullPath, "rb+")) != 0;     
    }
 
        return false;
}
 
// Gets the size of .img archive in bytes
unsigned __int64 IMG::GetImgArchiveSize()
{
    if(this -> IMG_Handle)
    {
        auto currentPos = _ftelli64(this -> IMG_Handle);
        _fseeki64(this -> IMG_Handle, 0, SEEK_END);
 
        unsigned __int64 sizeOfArchive = _ftelli64(this -> IMG_Handle);
 
        _fseeki64(this -> IMG_Handle, currentPos, SEEK_SET);
        return sizeOfArchive;
    }
    else
        return UNDEFINED;
}
 
// Gets size of unused space in .img file
unsigned __int64 IMG::GetSizeOfUnusedSpace()
{
    auto sortedListByPosition = this -> ListOfEntries;
 
    this -> SortListOfEntriesByPositionAndSize(sortedListByPosition);
 
    unsigned __int64 UnusedSpace = 0;
 
    if(sortedListByPosition.size() >= 1)
    {   
        size_t headerSize = GET_ALIGNED_SIZE(GetEndOfHeaderDataPastTheListOfFiles(), IMG_BLOCK_SIZE);
        UnusedSpace = sortedListByPosition.front().Position * IMG_BLOCK_SIZE - headerSize;
 
        auto sortedEntry = sortedListByPosition.begin();
 
        while(sortedEntry < sortedListByPosition.end() - 1)
        {
            signed __int64 UnusedSpaceItem = ((sortedEntry + 1) -> Position - (sortedEntry -> Position + sortedEntry -> GetFilesizeAllignedToBlocks() / IMG_BLOCK_SIZE))*IMG_BLOCK_SIZE;
 
            if((signed int)UnusedSpaceItem > 0)
                UnusedSpace += UnusedSpaceItem;         
 
            sortedEntry++;
        }   
        UnusedSpace += this -> GetImgArchiveSize() - (sortedListByPosition.back().Position * IMG_BLOCK_SIZE + sortedListByPosition.back().GetFilesizeAllignedToBlocks());       
 
        return UnusedSpace;
    }
    else
    {
        size_t headerSize = GET_ALIGNED_SIZE(GetEndOfHeaderDataPastTheListOfFiles(), IMG_BLOCK_SIZE);
        unsigned __int64 IMG_size = this -> GetImgArchiveSize();
        return IMG_size > headerSize ? IMG_size - headerSize : 0;
    }
}
 
// Retrieves the number of files inside of IMG archive
DWORD IMG::GetFileCount()
{
    return this -> ListOfEntries.size();
}
 
// Adds or replaces file if exists
void IMG::AddOrReplaceFile(const char* name, const void* ptr, size_t size)
{
    DWORD index = this -> GetFileIndexByName(name);
 
    if(index != UNDEFINED)
        this -> ReplaceSingleFile(index, ptr, size);
    else
        this -> AddFile(name, ptr, size);
}
 
// Adds file
void IMG::AddFile(const char* name, const void* ptr, size_t size)
{   
    unsigned __int64 PositionOfNewFile = this -> FindFirstEmptySpaceForFile(size, UNDEFINED);
 
#ifdef IMG_DEBUG    
    if(debugFile)
    {
        char text[256] = "\nAdded file \"";
        strcat(text, name);
        strcat(text, "\", Position: 0x");
 
        itoa (PositionOfNewFile, text + strlen(text), 16);
        strcat(text, ", Size: ");
        itoa (size, text + strlen(text), 16);
 
        fwrite(text, strlen(text), 1, debugFile);
    }
#endif
    
 
    this -> ListOfEntries.push_back(IMG_Entry(this));
    IMG_Entry& currentEntry = this -> ListOfEntries.back();
 
    _fseeki64(this -> IMG_Handle, PositionOfNewFile, SEEK_SET);
    
    size_t sizeInBlocks = this -> WriteAllignedFileToIMGblocks(ptr, size);  
    
    currentEntry.Position = (DWORD) (PositionOfNewFile / IMG_BLOCK_SIZE);
 
    if(archiveVersion == IMG_VERSION_3_UNENCRYPTED || archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        currentEntry.SizeInBytes = size;
    else
    {
        currentEntry.SizeSecondPriority = sizeInBlocks;
        currentEntry.SizeFirstPriority = NULL;
    }
 
    strncpy_s(currentEntry.Name, name,
        (archiveVersion == IMG_VERSION_1 || archiveVersion == IMG_VERSION_2) ?
            _countof(((IMG_version2_tableItem*)0) -> Name) - 1 : _countof(currentEntry.Name)-1);
 
    currentEntry.UpdateFileNameHash();  
 
    if(archiveVersion == IMG_VERSION_3_UNENCRYPTED || archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        this -> FilenamesSize += strlen(currentEntry.Name) + 1;
    
    this -> WriteListOfEntries();   
}
 
// Replaces file depending on index
void IMG::ReplaceSingleFile(DWORD index, const void* ptr, size_t size)
{
    unsigned __int64 PositionOfNewFile = this -> FindFirstEmptySpaceForFile(size, index);
 
    IMG_Entry& currentEntry = this -> at(index);
 
    _fseeki64(this -> IMG_Handle, PositionOfNewFile, SEEK_SET);
    size_t sizeInBlocks = this -> WriteAllignedFileToIMGblocks(ptr, size);
    
    currentEntry.Position = (DWORD)(PositionOfNewFile / IMG_BLOCK_SIZE);
 
    if(archiveVersion == IMG_VERSION_3_UNENCRYPTED || archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        currentEntry.SizeInBytes = size;
    else
    {
        if(currentEntry.SizeFirstPriority)
                currentEntry.SizeFirstPriority = sizeInBlocks;
        else
            currentEntry.SizeSecondPriority = sizeInBlocks;
    }
 
    this -> WriteListOfEntries();
}
 
// Renames a file
void IMG::RenameFile(DWORD index, const char* NewName)
{
    auto& FileInfo = this -> ListOfEntries.begin() + index;
 
    if(archiveVersion == IMG_VERSION_3_UNENCRYPTED || archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        FilenamesSize -= strlen(FileInfo -> Name) + 1;
 
    strncpy_s(FileInfo -> Name, NewName,
        (archiveVersion == IMG_VERSION_1 || archiveVersion == IMG_VERSION_2) ?
            _countof(((IMG_version2_tableItem*)0) -> Name) - 1 : _countof(FileInfo -> Name)-1);
    FileInfo -> UpdateFileNameHash();
 
    if(archiveVersion == IMG_VERSION_3_UNENCRYPTED || archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        FilenamesSize += strlen(FileInfo -> Name) + 1;
    
    this -> WriteListOfEntries();
}
 
// Removes a file
void IMG::RemoveFile(DWORD index)
{
    if(index != UNDEFINED)
        this -> RemoveFile(this -> ListOfEntries.begin() + index);
}
 
 
// Removes files
void IMG::RemoveFiles(DWORD start, DWORD end)
{
    if(start != UNDEFINED && end != UNDEFINED)
        this -> RemoveFiles(this -> ListOfEntries.begin() + start, this -> ListOfEntries.begin() + end);
}
 
// Remove a file
std::vector<IMG::IMG_Entry>::iterator IMG::RemoveFile(std::vector<IMG::IMG_Entry>::const_iterator _Where)
{
    auto result = this -> ListOfEntries.erase(_Where);
 
    this -> WriteListOfEntries();
 
    return result;
}
 
// Removes files
std::vector<IMG::IMG_Entry>::iterator IMG::RemoveFiles(
    std::vector<IMG::IMG_Entry>::const_iterator _First_arg,
    std::vector<IMG::IMG_Entry>::const_iterator _Last_arg
    )
{
    auto result = this -> ListOfEntries.erase(_First_arg, _Last_arg);
 
    this -> WriteListOfEntries();
 
    return result;
}
 
// Gets index of file pointing to ListOfFiles
unsigned int IMG::GetFileIndexByName(const char* name)
{
 
    if(ListOfEntries.size())
    {
        unsigned long hash = GTASA_CRC32_fromUpCaseString(name);
 
        auto& entry = ListOfEntries.begin();
 
        do
        {
            if(entry -> NameHash == hash && !_stricmp(entry -> Name, name))
                return entry - ListOfEntries.begin();
 
            entry++;
        }
        while(entry < ListOfEntries.end());
    }
 
    return UNDEFINED;
}
 
// Checks if file with specified name exists and returns TRUE/FALSE
bool IMG::FileExists(const char* name)
{
    return GetFileIndexByName(name) != UNDEFINED;
}
 
// Gets filename for imported file, filename may be truncated if archive version is 1 or 2.
// Returns true if name is tr
errno_t IMG::GetFilenameForImportedFile(const char* lpFileName, char* lpFilePart, DWORD nBufferLength)
{
    DWORD NormalMaxSize = (archiveVersion == IMG_VERSION_1 || archiveVersion == IMG_VERSION_2) ?
                _countof(((IMG_version2_tableItem*)0) -> Name) : _countof(((IMG_Entry*)0) -> Name);
 
    char FullPath[_MAX_PATH];
    char* FileName;
 
    GetFullPathNameA(lpFileName, _countof(FullPath), FullPath, &FileName);
 
    size_t ThisSize = nBufferLength > NormalMaxSize ? NormalMaxSize : nBufferLength;    
    return strncpy_s(lpFilePart, ThisSize, FileName, _TRUNCATE);
}
 
 
// Access element
// Returns a reference to the file at position n in the vector.
std::vector<IMG::IMG_Entry>::reference IMG::at(std::vector<IMG::IMG_Entry>::size_type n)
{
    return this -> ListOfEntries.at(n);
}
 
// Access element
// Returns a reference to the file at position n in the vector.
std::vector<IMG::IMG_Entry>::const_reference IMG::at(std::vector<IMG::IMG_Entry>::size_type n) const
{
    return this -> ListOfEntries.at(n);
}
 
// Access file by name
// Returns a reference to the last element in the vector container.
std::vector<IMG::IMG_Entry>::reference IMG::GetFileRefByName(const char* name)
{
    return this -> at(this -> GetFileIndexByName(name));
}
 
// Return iterator to beginning
std::vector<IMG::IMG_Entry>::iterator IMG::begin()
{
    return this -> ListOfEntries.begin();
}
 
// Return iterator to beginning
std::vector<IMG::IMG_Entry>::const_iterator IMG::begin() const
{
    return this -> ListOfEntries.begin();
}
 
// Return iterator to end
std::vector<IMG::IMG_Entry>::iterator IMG::end()
{
    return this -> ListOfEntries.end();
}
 
// Return iterator to end
std::vector<IMG::IMG_Entry>::const_iterator IMG::end() const
{
    return this -> ListOfEntries.end();
}
 
// Return reverse iterator to reverse beginning
std::vector<IMG::IMG_Entry>::reverse_iterator IMG::rbegin()
{
    return this -> ListOfEntries.rbegin();
}
 
// Return reverse iterator to reverse beginning
std::vector<IMG::IMG_Entry>::const_reverse_iterator IMG::rbegin() const
{
    return this -> ListOfEntries.rbegin();
}
 
// Return reverse iterator to reverse end
std::vector<IMG::IMG_Entry>::reverse_iterator IMG::rend()
{
    return this -> ListOfEntries.rend();
}
 
// Return reverse iterator to reverse end
std::vector<IMG::IMG_Entry>::const_reverse_iterator IMG::rend() const
{
    return this -> ListOfEntries.rend();
}
 
// Access last element
// Returns a reference to the last element in the vector container.
std::vector<IMG::IMG_Entry>::reference IMG::back()
{
    return this -> ListOfEntries.back();
}
 
// Access last element
// Returns a reference to the last element in the vector container.
std::vector<IMG::IMG_Entry>::const_reference IMG::back() const
{
    return this -> ListOfEntries.back();
}
 
// Access first element
// Returns a reference to the first element in the vector container.
std::vector<IMG::IMG_Entry>::reference IMG::front()
{
    return this -> ListOfEntries.front();
}
 
// Access first element
// Returns a reference to the first element in the vector container.
std::vector<IMG::IMG_Entry>::const_reference IMG::front() const
{
    return this -> ListOfEntries.front();
}
 
// Get end of list entries and header
DWORD IMG::GetEndOfHeaderDataPastTheListOfFiles()
{
    switch (this -> archiveVersion)
    {
    case IMG_VERSION_1:
        return 32;  // watermark
    case IMG_VERSION_2:
        return
            8   // version, number of files
            + this -> ListOfEntries.size() * 32
            + 32;   // watermark
 
    case IMG_VERSION_3_UNENCRYPTED:
    case IMG_VERSION_3_ENCRYPTED:       
        return
            20  // header
            + this -> ListOfEntries.size() * 16
            + FilenamesSize
            + 32;   // watermark
    default:
        return UNDEFINED;
    }
}
 
// Moves files located in position before list of files to suitable position
void IMG::MoveFilesLocatedBeforeListOfFilesToSuitablePosition(FILE* imgHandle)
{
    DWORD treshold = this -> GetEndOfHeaderDataPastTheListOfFiles();    
        
    auto entry = ListOfEntries.begin();
    
    while (entry < ListOfEntries.end())
    {
        if(entry -> Position * IMG_BLOCK_SIZE < treshold)
        {
            _fseeki64(imgHandle, (unsigned __int64) entry -> Position * IMG_BLOCK_SIZE, SEEK_SET);
            size_t size = entry -> GetFilesizeAllignedToBlocks();
            char* loadedFile = new char[size];
            fread(loadedFile, 1, size, imgHandle);
                
            entry -> Position = (DWORD) (this -> FindFirstEmptySpaceForFile(size)) / IMG_BLOCK_SIZE;
 
            _fseeki64(imgHandle, (unsigned __int64)entry -> Position * IMG_BLOCK_SIZE, SEEK_SET);
            fwrite(loadedFile, 1, size, imgHandle);
            delete loadedFile;
        }
        entry++;
    }       
}
 
// Returns pattern of IMG validity
void IMG::GetPatternToCheckIfPositionIsValid(char* str)
{
    const char a[] = "\x5f\x5b\x6e\x70\x6a\x5f\x6d\x39\x33\x22\x4c\x51\x4c\x26\x6a\x74\x6a\x7d\x7e\x2c\x3e\x3c\x44\x10\x11\x12\x13\x14\x15\x16\x17\x18";
 
    char c;
 
    DWORD d = 0;
 
    do
    {
        c = a[d] - (char)d + 7;
        str[d] = c;
 
        d++;
    }
    while(d < 32);
}
 
// Tests if file position is valid
void IMG::TestIfPositionIsValid(FILE* imgHandle)
{
    char b[32];
    GetPatternToCheckIfPositionIsValid(b);
 
    fwrite(b, 1, 32, imgHandle);
}
 
// reads version 1 or 2 header
void IMG::ReadEntryOfVersion1And2Header(IMG_Entry& entry, FILE* file)
{
    fread(&entry.Position, 4, 1, file);
    fread(&entry.SizeSecondPriority, 2, 1, file);
    fread(&entry.SizeFirstPriority, 2, 1, file);
    fread(&entry.Name, 24, 1, file);
    entry.UpdateFileNameHash();
}
 
// writes version 1 or 2 header
void IMG::WriteListOfEntriesVersion1And2(FILE* file)
{
    IMG_version2_tableItem* pBuffer = new IMG_version2_tableItem [this -> ListOfEntries.size()];
 
    IMG_version2_tableItem* iBuffer = pBuffer;
 
    for_each(ListOfEntries.begin(), ListOfEntries.end(),
        [&] (IMG::IMG_Entry entry)
    {
        iBuffer -> Position = entry.Position;
        iBuffer -> SizeSecondPriority = entry.SizeSecondPriority;
        iBuffer -> SizeFirstPriority = entry.SizeFirstPriority;
 
        strncpy_s(iBuffer -> Name, entry.Name, _countof(((IMG_version2_tableItem*)0) -> Name) - 1);
        iBuffer++;
    }
    );
 
    fwrite(pBuffer, sizeof(IMG_version2_tableItem), this -> ListOfEntries.size(), file);
    delete pBuffer;
}
 
// Updates list of entries in IMG archive/DIR file
void IMG::WriteListOfEntries(FILE* imgHandle)
{
    if(this -> ListOfEntries.size())
    {
        vector<IMG_Entry>::iterator FileWithHighestPosition = max_element(ListOfEntries.begin(), ListOfEntries.end(),
        [](IMG_Entry a, IMG_Entry b) { return a.Position < b.Position; });
 
        fileChangeSize(this -> IMG_Handle, (unsigned __int64) FileWithHighestPosition -> Position * IMG_BLOCK_SIZE + FileWithHighestPosition -> GetFilesizeAllignedToBlocks());
    }
    else
        fileChangeSize(this -> IMG_Handle, GET_ALIGNED_SIZE(GetEndOfHeaderDataPastTheListOfFiles(), IMG_BLOCK_SIZE));
 
    if(!imgHandle)
        imgHandle = this -> IMG_Handle;
 
    if(archiveVersion == IMG_VERSION_1)
    {
        this -> MoveFilesLocatedBeforeListOfFilesToSuitablePosition(imgHandle);
 
        fseek(imgHandle, 0, SEEK_SET);
        this -> TestIfPositionIsValid(imgHandle);
 
        fileChangeSize(this -> DIR_Handle, 0);
        _fseeki64(this -> DIR_Handle, 0, SEEK_SET);     
 
        this -> WriteListOfEntriesVersion1And2(this -> DIR_Handle);     
    }
    else if(archiveVersion == IMG_VERSION_2)
    {
        this -> MoveFilesLocatedBeforeListOfFilesToSuitablePosition(imgHandle);
 
        fseek(imgHandle, 4, SEEK_SET);      // number of files
            
        DWORD numberOfFiles = this -> ListOfEntries.size();
        fwrite(&numberOfFiles, 4, 1, imgHandle);
 
        this -> WriteListOfEntriesVersion1And2(imgHandle);
 
        this -> TestIfPositionIsValid(imgHandle);
    }
    else if(archiveVersion == IMG_VERSION_3_UNENCRYPTED || archiveVersion == IMG_VERSION_3_UNENCRYPTED)
    {
        this -> MoveFilesLocatedBeforeListOfFilesToSuitablePosition(imgHandle);
 
        fseek(imgHandle, 0, SEEK_SET);
    
        size_t BeginningSizeAlligned = GET_ALIGNED_SIZE(GetEndOfHeaderDataPastTheListOfFiles(), IMG_BLOCK_SIZE);
        char* pBeginning = new char[BeginningSizeAlligned];
 
        char* iBeginning = pBeginning;
        this -> WriteVersion3HeaderToMemory((IMG_version3_header*)iBeginning);
 
        iBeginning += sizeof(IMG_version3_header);
 
        IMG_version3_tableItem* ItemDescription = (IMG_version3_tableItem*) iBeginning;
 
        for(auto& entry = this -> ListOfEntries.begin(); entry < this -> ListOfEntries.end(); entry++, ItemDescription++)
        {
            ItemDescription -> SizeInBytes = entry -> SizeInBytes;
            ItemDescription -> ResourceType = entry -> ResourceType;
            ItemDescription -> Position = entry -> Position;
            ItemDescription -> SizeInBlocks = (WORD)GET_ALIGNED_SIZE_IN_BLOCKS(entry -> SizeInBytes, IMG_BLOCK_SIZE);
            ItemDescription -> Unknown = NULL;
        }
 
        char* Filenames = (char*) ItemDescription;
        for(auto& entry = this -> ListOfEntries.begin(); entry < this -> ListOfEntries.end(); entry++)
        {
            unsigned int i;
 
            for(i = 0; entry -> Name[i]; i++)
                *(Filenames++) = entry -> Name[i];
 
            *(Filenames++) = NULL;
        }
 
        GetPatternToCheckIfPositionIsValid(Filenames);
 
        fwrite(pBeginning, BeginningSizeAlligned, 1, imgHandle);
 
        delete pBeginning;
    }
}
 
// Writes file content alligned to IMG_BLOCK_SIZE
// Returned value is number of blocks written ( realSize / IMG_BLOCK_SIZE )
size_t IMG::WriteAllignedFileToIMGblocks(const void* ptr, size_t size)
{
    fwrite(ptr, 1, size, this -> IMG_Handle);
    size_t allignedSize = GET_ALIGNED_SIZE(size, IMG_BLOCK_SIZE);
 
    size_t sizeToAllign = allignedSize - size;
    char contentToAllign[2048];
    memset (contentToAllign, NULL, sizeToAllign);
 
    fwrite(contentToAllign, 1, sizeToAllign, this -> IMG_Handle);
 
    return allignedSize / IMG_BLOCK_SIZE;
}
 
// Writes IMG archive version 3 header to memory.
void IMG::WriteVersion3HeaderToMemory(IMG_version3_header* header)
{
    header -> MagicID = GTAIV_MAGIC_ID;
    header -> Version = 3;
    header -> NumberOfItems = this -> ListOfEntries.size();
    header -> TableOfItemsSize = header -> NumberOfItems * sizeof(IMG_version3_tableItem) + this -> FilenamesSize;
    header -> SingleTableItemSize = sizeof(IMG_version3_tableItem);
    header -> Unknown = NULL;
}
 
// Sorts an array by
// 1. Position
// 2. Size
void IMG::SortListOfEntriesByPositionAndSize(std::vector<IMG_Entry>& list)
{
    sort(list.begin(), list.end(),
        [](IMG_Entry a, IMG_Entry b) -> bool
    {
        size_t a_filesize = a.GetFilesizeAllignedToBlocks();
        size_t b_filesize = b.GetFilesizeAllignedToBlocks();
 
            return
                a.Position < b.Position ? true :
                a.Position > b.Position ? false :
 
                a_filesize < b_filesize ? true :
                b_filesize > b_filesize;
    }
    );
}
 
// Finds a first free space for target file
unsigned __int64 IMG::FindFirstEmptySpaceForFile(size_t filesize, DWORD overwrittenFileIndex)
{
    filesize = GET_ALIGNED_SIZE_IN_BLOCKS(filesize, IMG_BLOCK_SIZE);
 
    auto sortedListByPosition = this -> ListOfEntries;
 
    if(overwrittenFileIndex != UNDEFINED)
        sortedListByPosition.erase(sortedListByPosition.begin() + overwrittenFileIndex);
    
    this -> SortListOfEntriesByPositionAndSize(sortedListByPosition);
 
    if(sortedListByPosition.size() >= 1)
    {
        auto sortedEntry = sortedListByPosition.begin();
        
        while(sortedEntry < sortedListByPosition.end() - 1)
        {
            __int64 FreeSpace = (sortedEntry + 1) -> Position - (sortedEntry -> Position + sortedEntry -> GetFilesizeAllignedToBlocks() / IMG_BLOCK_SIZE);
 
            if(FreeSpace >= filesize)                               
                return (unsigned __int64)sortedEntry -> Position * IMG_BLOCK_SIZE + sortedEntry -> GetFilesizeAllignedToBlocks();
 
            sortedEntry++;
        }
        
        return (unsigned __int64)sortedListByPosition.back().Position * IMG_BLOCK_SIZE + sortedListByPosition.back().GetFilesizeAllignedToBlocks();
    }
    else
        return GET_ALIGNED_SIZE(GetEndOfHeaderDataPastTheListOfFiles(), IMG_BLOCK_SIZE);
}
 
// Outputs list of entries specified as argument
void IMG::DebugListOfEntries(std::vector<IMG_Entry>& list)
{
    for(auto entry = list.begin(); entry < list.end(); entry++)
    {
        cout << endl
            << (entry - list.begin())
            << " Offset: " << (unsigned __int64)entry -> Position * IMG_BLOCK_SIZE;
 
        if(archiveVersion == IMG_VERSION_1 || archiveVersion == IMG_VERSION_2)
            cout << " 2nd size: " << entry -> SizeSecondPriority * IMG_BLOCK_SIZE << " 1st size: " << entry -> SizeFirstPriority * IMG_BLOCK_SIZE;
        else
            cout << " Size in bytes: " << entry -> SizeInBytes << " ResourceType: " << (DWORD)entry -> ResourceType;
 
        cout << " Name: " << entry -> Name;
    }
 
}
 
// Outputs ListOfEntries
void IMG::DebugListOfEntries()
{
    this -> DebugListOfEntries(this -> ListOfEntries);
}
 
// Constructor
IMG::IMG_Entry::IMG_Entry(IMG * IMG_Instance)
{
    this -> IMG_Instance = IMG_Instance;
 
    this -> Position = 0;
    this -> SizeSecondPriority = 0;
    this -> SizeFirstPriority = 0;
    this -> SizeInBytes = 0;
    this -> ResourceType = RESOURCE_UNDEFINED;
    this -> Name[0] = NULL;
 
    this -> curPos = 0;
}
 
void IMG::IMG_Entry::UpdateFileNameHash()
{
    this -> NameHash = GTASA_CRC32_fromUpCaseString(this -> Name);
}
 
// Returns pointer to file name.
const char* IMG::IMG_Entry::GetFilename()
{
    return this -> Name;
}
 
// Reads whole file, doesn't affect current file position (curPos)
// Returns number of bytes read.
size_t IMG::IMG_Entry::ReadEntireFile(void* ptr)
{
    _fseeki64(this -> IMG_Instance -> IMG_Handle, (unsigned __int64) this ->Position * IMG_BLOCK_SIZE, SEEK_SET);
 
    size_t Filesize = this -> GetFilesize();
    fread(ptr, 1, Filesize, this -> IMG_Instance -> IMG_Handle);
    return Filesize;
}
 
// Reads to memory
size_t IMG::IMG_Entry::Read(void* Ptr, size_t Size)
{
    if(this -> curPos < this -> GetFilesize())
    {
        size_t SizeToRead = this -> curPos + Size > this -> GetFilesize() ? this -> GetFilesize() - this -> curPos : Size;
 
        this -> Seek(0, SEEK_CUR);
 
        size_t n_readBytes = fread(Ptr, 1, SizeToRead, this -> IMG_Instance -> IMG_Handle);
        this -> curPos += n_readBytes;
 
        return n_readBytes;
    }
    else 
        return false;
}
 
// Reads one byte
char IMG::IMG_Entry::ReadC()
{
    if(this -> curPos < this -> GetFilesize())
    {
        this -> Seek(0, SEEK_CUR);
        char result;
        this -> curPos += fread(&result, 1, 1, this -> IMG_Instance -> IMG_Handle);
        
        return result;
    }
    else
        return -1;
}
 
// Get file size in bytes
size_t IMG::IMG_Entry::GetFilesize()
{
    if(this ->IMG_Instance -> archiveVersion == IMG_VERSION_3_ENCRYPTED
        || this ->IMG_Instance ->  archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        return this -> SizeInBytes;
    else
    {
        size_t realSize = this -> SizeFirstPriority ? this -> SizeFirstPriority : this -> SizeSecondPriority;
        realSize *= IMG_BLOCK_SIZE;
        return realSize;
    }
}
 
// Get file size in blocks
size_t IMG::IMG_Entry::GetFilesizeAllignedToBlocks()
{
    if(this ->IMG_Instance -> archiveVersion == IMG_VERSION_3_ENCRYPTED
        || this ->IMG_Instance ->  archiveVersion == IMG_VERSION_3_UNENCRYPTED)
        return GET_ALIGNED_SIZE(this -> SizeInBytes, IMG_BLOCK_SIZE);
    else
    {
        size_t realSize = this -> SizeFirstPriority ? this -> SizeFirstPriority : this -> SizeSecondPriority;
        realSize *= IMG_BLOCK_SIZE;
        return realSize;
    }
}
 
// Check End-of-File indicator
bool IMG::IMG_Entry::isEOF()
{
    return this -> curPos >= this -> GetFilesize();
}
 
// Seek to certain position
bool IMG::IMG_Entry::Seek(unsigned int offset, int origin)
{
    bool result = false;
    if(origin == SEEK_SET)
    {
        if(offset <= this -> GetFilesize())
        {
            this -> curPos = offset;
            result = true;
        }
    }
    else if(origin == SEEK_CUR)
    {
        if(this -> curPos + offset <= this -> GetFilesize())
        {
            this -> curPos += offset;
            result = true;
        }
    }
    else if(origin == SEEK_END)
    {
        if(this -> curPos + this -> GetFilesize() + offset <= this -> GetFilesize())
        {
            this -> curPos += this -> GetFilesize() + offset;
            result = true;
        }
    }
 
    return _fseeki64(this -> IMG_Instance -> IMG_Handle, (unsigned __int64)this -> Position * IMG_BLOCK_SIZE + this -> curPos, SEEK_SET) != 0;
}
 
// Returns current position
unsigned int IMG::IMG_Entry::Tell()
{
    return this -> curPos;
}
GTASA_CRC32.cpp
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
#include "stdafx.h"
#include "GTASA_CRC32.h"
 
// table used in CRC calculation
const unsigned long GTASA_CRC32_table[256] = {
    0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
    0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
    0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
    0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
    0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
    0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
    0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
    0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
    0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
    0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
    0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
    0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
    0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
    0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
    0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
    0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
    0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
    0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
    0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
    0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
    0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
    0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
    0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
    0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
    0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
    0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
    0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
    0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
    0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
    0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
    0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
    0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
    0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
    0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
    0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
    0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
    0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
    0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
    0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
    0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
    0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
    0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
    0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
    0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
    0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
    0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
    0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
    0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
    0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
    0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
    0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
    0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
    0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
    0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
    0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
    0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
    0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
    0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
    0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
    0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
    0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
    0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
    0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
    0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
 
unsigned long GTASA_CRC32(const char* string)
{
    register unsigned long reg = 0xFFFFFFFF;  // register for CRC
 
    // CRC calculation
    while(*string)
    {
        reg = (reg >> 8) ^ GTASA_CRC32_table[*string ^ (reg & 0xFF)];
        string++;
    }
    return reg;
}
 
unsigned long GTASA_CRC32_fromString(const char* string)
{
    register unsigned long reg = 0xFFFFFFFF;  // register for CRC
 
    // CRC calculation
    while(*string)
    {
        reg = (reg >> 8) ^ GTASA_CRC32_table[*string ^ (reg & 0xFF)];
        string++;
    } 
    return reg;
}
 
unsigned long GTASA_CRC32_fromUpCaseString(const char* string)
{
    register unsigned long reg = 0xFFFFFFFF;  // register for CRC
 
    // CRC calculation
    while(*string)
    {
        reg = (reg >> 8) ^ GTASA_CRC32_table[toupper(*string) ^ (reg & 0xFF)];
        string++;
    } 
    return reg;
}
 
Текущее время: 04:44. Часовой пояс GMT +3.
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2016, vBulletin Solutions, Inc.
Рейтинг@Mail.ru