C++ Using pointers on structure and saving them on files -
soo have issue, im using pointers on structures , saving values on file
struct compracli{ char nomeartigo[50]; char codigo[50]; char nomecli[50]; char data[50]; }; int compra(int l){ compracli *ptr, d; file *arquivo; ptr = &d; if((arquivo = fopen("compras.dat", "rb+")) !=null){ //colocar apontadores dentro dos arquivos system("cls"); cout<<"adicinar um pedido de compra!"<<endl; cin.sync(); cout<<"adicione o nome artigo: "; cin >> (*ptr).nomeartigo; fwrite(ptr->nomeartigo, sizeof(ptr->nomeartigo), 1, arquivo); cin.sync(); cout<<"adicione o codigo artigo: "; cin >> (*ptr).codigo; fwrite(ptr->codigo, sizeof(ptr->codigo), 2, arquivo); cin.sync(); cout<<"adicione o nome cliente: "; cin >> (*ptr).nomecli; fwrite(ptr->nomecli, sizeof(ptr->nomecli), 3, arquivo); cin.sync(); cout<<"adicione data de encomenda: "; cin >> (*ptr).data; fwrite(ptr->data, sizeof(ptr->data), 4, arquivo); cin.sync(); }else{ cout<<"erro na base de dados, de momento nao poderĂ¡ aceder, tente mais tarde"<<endl; } fclose(arquivo); return 0;
the problem is, saving first value, means (*ptr).nomeartigo . @ first thought because of buffer, maybe full, soo tried clean using cin.sync(); still didnt worked out. thought might problem using "lines" example "fwrite(ptr->data, sizeof(ptr->data), 4, arquivo);" "4", thought saving in same line why causing problems. still didnt worked out! im out of ideas, knows how to?
cin >> (*ptr).nomeartigo; fwrite(ptr->nomeartigo, sizeof(ptr->nomeartigo), 1, arquivo);
nomeartigo
char
array. writes bytes in array, including trailing \0
byte operator>>
puts there, , uninitialized data follows. may or may not wrong. depends on how read back, did not show code.
fwrite(ptr->codigo, sizeof(ptr->codigo), 2, arquivo);
this, , remaining fwrite
()s wrong.
this writes sizeof(ptr->codigo)*2
bytes. not want. there sizeof(ptr->codigo)
bytes write here.
all fwrite
()s, except first ones write much. third parameter fwrite()
not line number, of kind.
additionally, since c++, should not using file *
, rather std::fstream
. also, operator>>
on char
array not bound-limited, , vulnerable buffer overruns.
Comments
Post a Comment