0

I have a text file written 10some information#11some more information#12and some more information#

10,11,12 are sentence id and should always be 2 bytes

I need to build a binary file from this text file, with the help of which I will then need to read sentences by id from a text file

In a binary file, each line should contain the following: sentence id, position of the beginning of the sentence, length of the string (sentence)

I managed to build a binary file, but I didn’t manage to read the information using it, the program shows that there are no such id, but I don’t understand why

#include <iostream>
#include <locale>
#include <string.h>

using namespace std;


int main()
{
    FILE *poem, *index;
    int N = 4096, len;
    char *str= new char[N];
    if (!(poem = fopen("poem.txt", "r")))
    {
        cout << "File not found";
        return 0;
    }
    fgets(str, N, poem);

index = fopen("index.txt", "w+b");

int pos1 = 2, pos_b;
char* pos = str+pos1, *pstr=str;
fwrite(pstr, sizeof(char), 2, index);
fwrite(&pos1, sizeof(int), 1, index);
for (int i = 2; *pstr != '\0'; ++i, pstr++) {
    if (*pstr == '#') {
        len = pstr - pos;
        fwrite(&len, sizeof(int), 1, index);
        pos = pstr + pos1;
        if (*(pstr+1)!='\0') {
           fputs("\n", index);
           fwrite(pstr+1, sizeof(char), 2, index);
           pos_b = i + 3;
           fwrite(&pos_b, sizeof(int), 1, index);
        }  
    }
}

pos_b = 0;
len = 0;
fseek(index, 0, SEEK_SET);
fseek(poem, 0, SEEK_SET);
char* id = new char[3], * id_f = new char[3], * sent = new char[N];
int have_id = 0;
cout << "Enter the id of the offer you want to read" << endl;
cin >> id;

while (!feof(index)) {
    fread(id_f, sizeof(char), 2, index);
     if (strcmp(id_f,id)==0) { 
        fread(&pos_b, sizeof(int), 1, index);
        fread(&len, sizeof(int), 1, index);
        fseek(poem, pos_b, SEEK_SET);
        fgets(sent, len + 1, poem);
        cout << sent << endl;
        have_id = 1;
        
    }
    else {
         fread(id_f, sizeof(char), 3, index);
    }
    
  //  fseek(index, 5, SEEK_CUR);
}
if (have_id == 0) {
    cout << "There is no such id" << endl;
}

fclose(index);
fclose(poem);
delete[] str;


return 0;

}

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
Kit_ri
  • 39
  • 3

0 Answers0