2
I have a code where I create and then read a file .dat
with information from sales records, such as date, time, price, etc. I can do a search by date, for example, and generate another file .dat
only with the purchase records of that date, however, when I use the read function to read this new generated file it cannot access the information that is in the record, the program tops, as if it were some improper access of the pointer, as I see.
header. h
class RegistroVenda{ // classe com os dados que vou salvar no arquivo
public:
string data, hora, cidade, etc.... ;
};
file.cpp
RegistroVenda * v = new RegistroVenda(); // uso v para acessar a classe, deixo aqui em cima pra ficar global
void Leitura(string nome_arquivo){ // na primeira chamada da função tudo vai funcionar
fstream arquivo(nome_arquivo, ios::in|ios::binary); ... ok
//verifico se abriu certo... ok
//calculo tamanho do arquivo... ok
for(int i=0; i<tamanho_arquivo; i++){
/* .read() ta lendo um bloco de dados e passando pra v, que é global,
então ele deveria acessar os atributos da classe corretamente */
arquivo.read( (char*)v, sizeof(RegistroVenda) );
cout << "cidade = " << v->cidade << endl; // só que quando tento acessar a cidade por exemplo, da erro
}
}
The first time I run the program it will read a file .txt
, will save the data to a file .dat
, then I can search this file .dat
and the search result I saved in another file .dat
. So far everything works beauty.
Then I’ll call the same function you read before (and it worked) to read the search result, only that’s where the program tops. When it’s time to access attributes ( v->cidade
for example) it tops.
Why v
can’t access the contents of the variables the second time I rotate the function? It seems that, when rotating a second time, he loses the reference of something and ends up making an improper access.
Post an entire, compileable program. Post an example of the txt file to have a minimum playable problem for anyone who wants to help. Don’t use global variables. Never. Use a Sale class and the operations you need. Work with memory sales if possible, using one of the many containers the language offers. And only record at the end.
– arfneto