Why my program doesn't read data from the binary file in C++?
Project Detail :: I have been trying to do a project which i named Expense Management system.
General code Info:: I have a class "expense" it has only two function set and get data.I have a main() function and also inside it i have menu() function.
function menu :: there are 4 cases but only two of them are core function ,case 1:: write data into the file( Expense detail) and case 2 Read the data and display it .
Problem to be fixed :: My below case 2 ,Function code doesn't work ie it doesn't display the content of the file
The Below code is fixed according to the recommendation commented below in Answers ::
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class expense{
public:
//string
char date[20];
// string
char title[20];
double exp;
public:
void set_data(){
cout<<"nDate should be in the formatn i.e. day/moth/year eg 12/5/2018n";
cout<<"Enter the whole daten";
cin>>date;
cout<<"Give title for expensen";
cin>>title;
cout<<"Enter the total expensen";
cin>>exp;
}
void get_data(){
cout<<"tDate :: ";
cout<<date;
cout<<"tTitle :: ";
cout<<title;
cout<<"tExpense :: ";
cout<<exp;
}
};
//header files
void menu();
//global variable's
int count=0;
double tot=0;
//main function
int main()
{
menu(); //calling function
return 0;
}
//function definition
void menu(){
int ch;
int n;
int i;
char choice;
string dd;
int flag=0;
expense exe;
fstream fp;//file obj
fp.open("test.dat",ios::app | ios::out | ios::in | ios::binary);
//opening file in different modes
if (!fp.good())
cout << "file errorn";
//loop below
do {
cout << "n --------------------------------------- n";
cout << "Welcome to the Expense Management System" << endl;
cout << "1.Enter the expense.n";
cout << "2.Display all the expenses.n";
cout << "3.Find expense for a particular date.n";
cout << "4.Display the total expenditure.n";
cout << "nEnter the choice :: n";
cin >> ch;
switch (ch) {
// case 1:: write data into the file
case 1:
exe.set_data();
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
break;
case 2:
//case 2 read all the data from the file
fp.seekg(0,ios::beg);
cout << "All the expenses are listed below ::n";
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense));
exe.get_data();
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
cout<<"n";
exe.get_data();
}
break;
case 3:
//case 3 find the expense data from the file of the particular date
fp.seekg(0,ios::beg);
cout<<"Enter the date:n";
cin>>dd;
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
if((strcmp(exe.date,dd)==0)
{
flag=1;
exe.get_data();
}
cout<<"n";
}
if(flag==0){
cout<<"Kindly Enter The Correct Daten";
}
//fp.close();
break;
case 4:
//case 4:: calculates the total expense amount
fp.seekg(0,ios::beg);
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
tot+=exe.exp;
}
cout << "The Total Expenditure is ::n"<<tot<<endl;
//fp.close();
break;
}
cout<<"nDo you want to access the Main Menu?(y/n)n";
cin>>choice;
}while(choice =='Y' || choice =='y');
}
Solution :::
My problem is finally solved.I have drawn a conclusion since the program is working fine.
Things to be fixed in the above program ::-
1)While working with file.write() and file.read() function we should not include string variable so i changed every string variable into character array(IE each variable of fixed then no need to allocate memory additionally )
Reason ::std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast(thanks to eukaryota )
2) I should reset the pointer to the start of the file every time before reading data from the file.( thanks to kerrytazi )
E.G::
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
3)Yes i have use the " reinterpret_cast<char *> " and it works cause i have used "char array" data type.
4)Instead of writing a binary file we can also serialize a object in C++ and write data into text file also.
link :: https://thispointer.com/c-how-to-read-or-write-objects-in-file-serializing-deserializing-objects/
5)TO read multiple data from a file using while loop will not work if we use while( !file.eof()) which is explained by the link below.
link :: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong
c++
add a comment |
Project Detail :: I have been trying to do a project which i named Expense Management system.
General code Info:: I have a class "expense" it has only two function set and get data.I have a main() function and also inside it i have menu() function.
function menu :: there are 4 cases but only two of them are core function ,case 1:: write data into the file( Expense detail) and case 2 Read the data and display it .
Problem to be fixed :: My below case 2 ,Function code doesn't work ie it doesn't display the content of the file
The Below code is fixed according to the recommendation commented below in Answers ::
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class expense{
public:
//string
char date[20];
// string
char title[20];
double exp;
public:
void set_data(){
cout<<"nDate should be in the formatn i.e. day/moth/year eg 12/5/2018n";
cout<<"Enter the whole daten";
cin>>date;
cout<<"Give title for expensen";
cin>>title;
cout<<"Enter the total expensen";
cin>>exp;
}
void get_data(){
cout<<"tDate :: ";
cout<<date;
cout<<"tTitle :: ";
cout<<title;
cout<<"tExpense :: ";
cout<<exp;
}
};
//header files
void menu();
//global variable's
int count=0;
double tot=0;
//main function
int main()
{
menu(); //calling function
return 0;
}
//function definition
void menu(){
int ch;
int n;
int i;
char choice;
string dd;
int flag=0;
expense exe;
fstream fp;//file obj
fp.open("test.dat",ios::app | ios::out | ios::in | ios::binary);
//opening file in different modes
if (!fp.good())
cout << "file errorn";
//loop below
do {
cout << "n --------------------------------------- n";
cout << "Welcome to the Expense Management System" << endl;
cout << "1.Enter the expense.n";
cout << "2.Display all the expenses.n";
cout << "3.Find expense for a particular date.n";
cout << "4.Display the total expenditure.n";
cout << "nEnter the choice :: n";
cin >> ch;
switch (ch) {
// case 1:: write data into the file
case 1:
exe.set_data();
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
break;
case 2:
//case 2 read all the data from the file
fp.seekg(0,ios::beg);
cout << "All the expenses are listed below ::n";
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense));
exe.get_data();
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
cout<<"n";
exe.get_data();
}
break;
case 3:
//case 3 find the expense data from the file of the particular date
fp.seekg(0,ios::beg);
cout<<"Enter the date:n";
cin>>dd;
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
if((strcmp(exe.date,dd)==0)
{
flag=1;
exe.get_data();
}
cout<<"n";
}
if(flag==0){
cout<<"Kindly Enter The Correct Daten";
}
//fp.close();
break;
case 4:
//case 4:: calculates the total expense amount
fp.seekg(0,ios::beg);
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
tot+=exe.exp;
}
cout << "The Total Expenditure is ::n"<<tot<<endl;
//fp.close();
break;
}
cout<<"nDo you want to access the Main Menu?(y/n)n";
cin>>choice;
}while(choice =='Y' || choice =='y');
}
Solution :::
My problem is finally solved.I have drawn a conclusion since the program is working fine.
Things to be fixed in the above program ::-
1)While working with file.write() and file.read() function we should not include string variable so i changed every string variable into character array(IE each variable of fixed then no need to allocate memory additionally )
Reason ::std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast(thanks to eukaryota )
2) I should reset the pointer to the start of the file every time before reading data from the file.( thanks to kerrytazi )
E.G::
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
3)Yes i have use the " reinterpret_cast<char *> " and it works cause i have used "char array" data type.
4)Instead of writing a binary file we can also serialize a object in C++ and write data into text file also.
link :: https://thispointer.com/c-how-to-read-or-write-objects-in-file-serializing-deserializing-objects/
5)TO read multiple data from a file using while loop will not work if we use while( !file.eof()) which is explained by the link below.
link :: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong
c++
Will Gladly appreciate each answer ,that each explained ans will provide me a relief .
– Dipesh sapkota
Nov 17 '18 at 18:32
Handy reading: stackoverflow.com/a/42440290/4581301
– user4581301
Nov 17 '18 at 19:30
add a comment |
Project Detail :: I have been trying to do a project which i named Expense Management system.
General code Info:: I have a class "expense" it has only two function set and get data.I have a main() function and also inside it i have menu() function.
function menu :: there are 4 cases but only two of them are core function ,case 1:: write data into the file( Expense detail) and case 2 Read the data and display it .
Problem to be fixed :: My below case 2 ,Function code doesn't work ie it doesn't display the content of the file
The Below code is fixed according to the recommendation commented below in Answers ::
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class expense{
public:
//string
char date[20];
// string
char title[20];
double exp;
public:
void set_data(){
cout<<"nDate should be in the formatn i.e. day/moth/year eg 12/5/2018n";
cout<<"Enter the whole daten";
cin>>date;
cout<<"Give title for expensen";
cin>>title;
cout<<"Enter the total expensen";
cin>>exp;
}
void get_data(){
cout<<"tDate :: ";
cout<<date;
cout<<"tTitle :: ";
cout<<title;
cout<<"tExpense :: ";
cout<<exp;
}
};
//header files
void menu();
//global variable's
int count=0;
double tot=0;
//main function
int main()
{
menu(); //calling function
return 0;
}
//function definition
void menu(){
int ch;
int n;
int i;
char choice;
string dd;
int flag=0;
expense exe;
fstream fp;//file obj
fp.open("test.dat",ios::app | ios::out | ios::in | ios::binary);
//opening file in different modes
if (!fp.good())
cout << "file errorn";
//loop below
do {
cout << "n --------------------------------------- n";
cout << "Welcome to the Expense Management System" << endl;
cout << "1.Enter the expense.n";
cout << "2.Display all the expenses.n";
cout << "3.Find expense for a particular date.n";
cout << "4.Display the total expenditure.n";
cout << "nEnter the choice :: n";
cin >> ch;
switch (ch) {
// case 1:: write data into the file
case 1:
exe.set_data();
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
break;
case 2:
//case 2 read all the data from the file
fp.seekg(0,ios::beg);
cout << "All the expenses are listed below ::n";
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense));
exe.get_data();
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
cout<<"n";
exe.get_data();
}
break;
case 3:
//case 3 find the expense data from the file of the particular date
fp.seekg(0,ios::beg);
cout<<"Enter the date:n";
cin>>dd;
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
if((strcmp(exe.date,dd)==0)
{
flag=1;
exe.get_data();
}
cout<<"n";
}
if(flag==0){
cout<<"Kindly Enter The Correct Daten";
}
//fp.close();
break;
case 4:
//case 4:: calculates the total expense amount
fp.seekg(0,ios::beg);
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
tot+=exe.exp;
}
cout << "The Total Expenditure is ::n"<<tot<<endl;
//fp.close();
break;
}
cout<<"nDo you want to access the Main Menu?(y/n)n";
cin>>choice;
}while(choice =='Y' || choice =='y');
}
Solution :::
My problem is finally solved.I have drawn a conclusion since the program is working fine.
Things to be fixed in the above program ::-
1)While working with file.write() and file.read() function we should not include string variable so i changed every string variable into character array(IE each variable of fixed then no need to allocate memory additionally )
Reason ::std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast(thanks to eukaryota )
2) I should reset the pointer to the start of the file every time before reading data from the file.( thanks to kerrytazi )
E.G::
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
3)Yes i have use the " reinterpret_cast<char *> " and it works cause i have used "char array" data type.
4)Instead of writing a binary file we can also serialize a object in C++ and write data into text file also.
link :: https://thispointer.com/c-how-to-read-or-write-objects-in-file-serializing-deserializing-objects/
5)TO read multiple data from a file using while loop will not work if we use while( !file.eof()) which is explained by the link below.
link :: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong
c++
Project Detail :: I have been trying to do a project which i named Expense Management system.
General code Info:: I have a class "expense" it has only two function set and get data.I have a main() function and also inside it i have menu() function.
function menu :: there are 4 cases but only two of them are core function ,case 1:: write data into the file( Expense detail) and case 2 Read the data and display it .
Problem to be fixed :: My below case 2 ,Function code doesn't work ie it doesn't display the content of the file
The Below code is fixed according to the recommendation commented below in Answers ::
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class expense{
public:
//string
char date[20];
// string
char title[20];
double exp;
public:
void set_data(){
cout<<"nDate should be in the formatn i.e. day/moth/year eg 12/5/2018n";
cout<<"Enter the whole daten";
cin>>date;
cout<<"Give title for expensen";
cin>>title;
cout<<"Enter the total expensen";
cin>>exp;
}
void get_data(){
cout<<"tDate :: ";
cout<<date;
cout<<"tTitle :: ";
cout<<title;
cout<<"tExpense :: ";
cout<<exp;
}
};
//header files
void menu();
//global variable's
int count=0;
double tot=0;
//main function
int main()
{
menu(); //calling function
return 0;
}
//function definition
void menu(){
int ch;
int n;
int i;
char choice;
string dd;
int flag=0;
expense exe;
fstream fp;//file obj
fp.open("test.dat",ios::app | ios::out | ios::in | ios::binary);
//opening file in different modes
if (!fp.good())
cout << "file errorn";
//loop below
do {
cout << "n --------------------------------------- n";
cout << "Welcome to the Expense Management System" << endl;
cout << "1.Enter the expense.n";
cout << "2.Display all the expenses.n";
cout << "3.Find expense for a particular date.n";
cout << "4.Display the total expenditure.n";
cout << "nEnter the choice :: n";
cin >> ch;
switch (ch) {
// case 1:: write data into the file
case 1:
exe.set_data();
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
break;
case 2:
//case 2 read all the data from the file
fp.seekg(0,ios::beg);
cout << "All the expenses are listed below ::n";
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense));
exe.get_data();
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
cout<<"n";
exe.get_data();
}
break;
case 3:
//case 3 find the expense data from the file of the particular date
fp.seekg(0,ios::beg);
cout<<"Enter the date:n";
cin>>dd;
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
if((strcmp(exe.date,dd)==0)
{
flag=1;
exe.get_data();
}
cout<<"n";
}
if(flag==0){
cout<<"Kindly Enter The Correct Daten";
}
//fp.close();
break;
case 4:
//case 4:: calculates the total expense amount
fp.seekg(0,ios::beg);
while (fp.read(reinterpret_cast<char *>(&exe), sizeof(expense)))
{
if(fp.gcount() != sizeof(exe))
{
cout << "read error, we didn't get the right number of bytesn";
break;
}
tot+=exe.exp;
}
cout << "The Total Expenditure is ::n"<<tot<<endl;
//fp.close();
break;
}
cout<<"nDo you want to access the Main Menu?(y/n)n";
cin>>choice;
}while(choice =='Y' || choice =='y');
}
Solution :::
My problem is finally solved.I have drawn a conclusion since the program is working fine.
Things to be fixed in the above program ::-
1)While working with file.write() and file.read() function we should not include string variable so i changed every string variable into character array(IE each variable of fixed then no need to allocate memory additionally )
Reason ::std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast(thanks to eukaryota )
2) I should reset the pointer to the start of the file every time before reading data from the file.( thanks to kerrytazi )
E.G::
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
3)Yes i have use the " reinterpret_cast<char *> " and it works cause i have used "char array" data type.
4)Instead of writing a binary file we can also serialize a object in C++ and write data into text file also.
link :: https://thispointer.com/c-how-to-read-or-write-objects-in-file-serializing-deserializing-objects/
5)TO read multiple data from a file using while loop will not work if we use while( !file.eof()) which is explained by the link below.
link :: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong
c++
c++
edited Nov 21 '18 at 17:22
Dipesh sapkota
asked Nov 17 '18 at 18:29
Dipesh sapkotaDipesh sapkota
82
82
Will Gladly appreciate each answer ,that each explained ans will provide me a relief .
– Dipesh sapkota
Nov 17 '18 at 18:32
Handy reading: stackoverflow.com/a/42440290/4581301
– user4581301
Nov 17 '18 at 19:30
add a comment |
Will Gladly appreciate each answer ,that each explained ans will provide me a relief .
– Dipesh sapkota
Nov 17 '18 at 18:32
Handy reading: stackoverflow.com/a/42440290/4581301
– user4581301
Nov 17 '18 at 19:30
Will Gladly appreciate each answer ,that each explained ans will provide me a relief .
– Dipesh sapkota
Nov 17 '18 at 18:32
Will Gladly appreciate each answer ,that each explained ans will provide me a relief .
– Dipesh sapkota
Nov 17 '18 at 18:32
Handy reading: stackoverflow.com/a/42440290/4581301
– user4581301
Nov 17 '18 at 19:30
Handy reading: stackoverflow.com/a/42440290/4581301
– user4581301
Nov 17 '18 at 19:30
add a comment |
2 Answers
2
active
oldest
votes
You need to move your file pointer back after writing to it.
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
How it works:
/* file: */
/* ^ */
fp.write("test", 4);
/* file: test */
/* ----^ */
fp.seekp(0, std::ios::beg);
/* file: test */
/* ^ */
fp.read(outBuffer, 4);
/* file: test */
/* ----^ */
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
@Dipeshsapkota just addfp.seekp(0, std::ios::beg);before yourwhileloop in the 2nd case, and all other cases, that reads whole file from begin of it.
– kerrytazi
Nov 18 '18 at 16:20
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
|
show 1 more comment
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense))
These will absolutely not do what you want to do here. There are only very few specific cases where this is works and even then the files written in this manner will not be portable.
The pointer obtained from reinterpret_cast<char*>(&exe) will point to the address of the object exe and reading from there will give you the object representation of the object exe, basically the actual bytes stored at that location in memory, which is not necessarily enough information to reconstruct the full state of the object.
Writing the byte sequence to a file and reloading it by reading from the file with the second code line will only be sufficient to reconstruct exe if exe has a TriviallyCopyable type. Informally, this concept requires, in addition to other things, that all data required to reconstruct the object state is located in the object's storage itself and not in another memory location linked via e.g. a pointer member. In your case std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast.
You should probably never use reinterpret_cast if you are not 100% sure what it does.
You need to serialize the expense structure properly and write it to the file in a format of your choosing. This is a non-trivial task if you want to do it properly. If you want to do it roughly, assuming there are no whitespaces in the strings, then:
fp << exe.date << exe.title << exe.exp << "n";
might be a way to do it.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53354241%2fwhy-my-program-doesnt-read-data-from-the-binary-file-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to move your file pointer back after writing to it.
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
How it works:
/* file: */
/* ^ */
fp.write("test", 4);
/* file: test */
/* ----^ */
fp.seekp(0, std::ios::beg);
/* file: test */
/* ^ */
fp.read(outBuffer, 4);
/* file: test */
/* ----^ */
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
@Dipeshsapkota just addfp.seekp(0, std::ios::beg);before yourwhileloop in the 2nd case, and all other cases, that reads whole file from begin of it.
– kerrytazi
Nov 18 '18 at 16:20
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
|
show 1 more comment
You need to move your file pointer back after writing to it.
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
How it works:
/* file: */
/* ^ */
fp.write("test", 4);
/* file: test */
/* ----^ */
fp.seekp(0, std::ios::beg);
/* file: test */
/* ^ */
fp.read(outBuffer, 4);
/* file: test */
/* ----^ */
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
@Dipeshsapkota just addfp.seekp(0, std::ios::beg);before yourwhileloop in the 2nd case, and all other cases, that reads whole file from begin of it.
– kerrytazi
Nov 18 '18 at 16:20
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
|
show 1 more comment
You need to move your file pointer back after writing to it.
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
How it works:
/* file: */
/* ^ */
fp.write("test", 4);
/* file: test */
/* ----^ */
fp.seekp(0, std::ios::beg);
/* file: test */
/* ^ */
fp.read(outBuffer, 4);
/* file: test */
/* ----^ */
You need to move your file pointer back after writing to it.
fp.write(...);
fp.seekp(0, std::ios::beg); /* set file pointer at the start of file */
fp.read(...);
How it works:
/* file: */
/* ^ */
fp.write("test", 4);
/* file: test */
/* ----^ */
fp.seekp(0, std::ios::beg);
/* file: test */
/* ^ */
fp.read(outBuffer, 4);
/* file: test */
/* ----^ */
edited Nov 17 '18 at 18:47
answered Nov 17 '18 at 18:42
kerrytazikerrytazi
29127
29127
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
@Dipeshsapkota just addfp.seekp(0, std::ios::beg);before yourwhileloop in the 2nd case, and all other cases, that reads whole file from begin of it.
– kerrytazi
Nov 18 '18 at 16:20
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
|
show 1 more comment
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
@Dipeshsapkota just addfp.seekp(0, std::ios::beg);before yourwhileloop in the 2nd case, and all other cases, that reads whole file from begin of it.
– kerrytazi
Nov 18 '18 at 16:20
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
I got your point eukaryota but would be really really really helpful if can write the non-trival code as you are mentioning that .
– Dipesh sapkota
Nov 18 '18 at 14:57
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
Also I will use << and Can tell me why are you mentioning whitespace and what's the relationship with my problem can you clarify please
– Dipesh sapkota
Nov 18 '18 at 15:42
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
I will give it a shot kerrytazi ,(I was out today sorry for the late reply )
– Dipesh sapkota
Nov 18 '18 at 15:44
@Dipeshsapkota just add
fp.seekp(0, std::ios::beg); before your while loop in the 2nd case, and all other cases, that reads whole file from begin of it.– kerrytazi
Nov 18 '18 at 16:20
@Dipeshsapkota just add
fp.seekp(0, std::ios::beg); before your while loop in the 2nd case, and all other cases, that reads whole file from begin of it.– kerrytazi
Nov 18 '18 at 16:20
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
Thanks i did the correction but still the the previously entered data is not being displayed .I will send the screen shot of it in the answer .
– Dipesh sapkota
Nov 18 '18 at 16:48
|
show 1 more comment
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense))
These will absolutely not do what you want to do here. There are only very few specific cases where this is works and even then the files written in this manner will not be portable.
The pointer obtained from reinterpret_cast<char*>(&exe) will point to the address of the object exe and reading from there will give you the object representation of the object exe, basically the actual bytes stored at that location in memory, which is not necessarily enough information to reconstruct the full state of the object.
Writing the byte sequence to a file and reloading it by reading from the file with the second code line will only be sufficient to reconstruct exe if exe has a TriviallyCopyable type. Informally, this concept requires, in addition to other things, that all data required to reconstruct the object state is located in the object's storage itself and not in another memory location linked via e.g. a pointer member. In your case std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast.
You should probably never use reinterpret_cast if you are not 100% sure what it does.
You need to serialize the expense structure properly and write it to the file in a format of your choosing. This is a non-trivial task if you want to do it properly. If you want to do it roughly, assuming there are no whitespaces in the strings, then:
fp << exe.date << exe.title << exe.exp << "n";
might be a way to do it.
add a comment |
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense))
These will absolutely not do what you want to do here. There are only very few specific cases where this is works and even then the files written in this manner will not be portable.
The pointer obtained from reinterpret_cast<char*>(&exe) will point to the address of the object exe and reading from there will give you the object representation of the object exe, basically the actual bytes stored at that location in memory, which is not necessarily enough information to reconstruct the full state of the object.
Writing the byte sequence to a file and reloading it by reading from the file with the second code line will only be sufficient to reconstruct exe if exe has a TriviallyCopyable type. Informally, this concept requires, in addition to other things, that all data required to reconstruct the object state is located in the object's storage itself and not in another memory location linked via e.g. a pointer member. In your case std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast.
You should probably never use reinterpret_cast if you are not 100% sure what it does.
You need to serialize the expense structure properly and write it to the file in a format of your choosing. This is a non-trivial task if you want to do it properly. If you want to do it roughly, assuming there are no whitespaces in the strings, then:
fp << exe.date << exe.title << exe.exp << "n";
might be a way to do it.
add a comment |
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense))
These will absolutely not do what you want to do here. There are only very few specific cases where this is works and even then the files written in this manner will not be portable.
The pointer obtained from reinterpret_cast<char*>(&exe) will point to the address of the object exe and reading from there will give you the object representation of the object exe, basically the actual bytes stored at that location in memory, which is not necessarily enough information to reconstruct the full state of the object.
Writing the byte sequence to a file and reloading it by reading from the file with the second code line will only be sufficient to reconstruct exe if exe has a TriviallyCopyable type. Informally, this concept requires, in addition to other things, that all data required to reconstruct the object state is located in the object's storage itself and not in another memory location linked via e.g. a pointer member. In your case std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast.
You should probably never use reinterpret_cast if you are not 100% sure what it does.
You need to serialize the expense structure properly and write it to the file in a format of your choosing. This is a non-trivial task if you want to do it properly. If you want to do it roughly, assuming there are no whitespaces in the strings, then:
fp << exe.date << exe.title << exe.exp << "n";
might be a way to do it.
fp.write(reinterpret_cast<char *>(&exe), sizeof(expense));
fp.read(reinterpret_cast<char *>(&exe), sizeof(expense))
These will absolutely not do what you want to do here. There are only very few specific cases where this is works and even then the files written in this manner will not be portable.
The pointer obtained from reinterpret_cast<char*>(&exe) will point to the address of the object exe and reading from there will give you the object representation of the object exe, basically the actual bytes stored at that location in memory, which is not necessarily enough information to reconstruct the full state of the object.
Writing the byte sequence to a file and reloading it by reading from the file with the second code line will only be sufficient to reconstruct exe if exe has a TriviallyCopyable type. Informally, this concept requires, in addition to other things, that all data required to reconstruct the object state is located in the object's storage itself and not in another memory location linked via e.g. a pointer member. In your case std::string does not fulfill the TriviallyCopyable requirement because, in order to hold strings of arbitrary length, it is allocating additional memory dynamically. This memory will not be part of the string's object representation and thus also not part of the object representation you acquire with the reinterpret_cast.
You should probably never use reinterpret_cast if you are not 100% sure what it does.
You need to serialize the expense structure properly and write it to the file in a format of your choosing. This is a non-trivial task if you want to do it properly. If you want to do it roughly, assuming there are no whitespaces in the strings, then:
fp << exe.date << exe.title << exe.exp << "n";
might be a way to do it.
edited Nov 18 '18 at 6:02
answered Nov 17 '18 at 18:40
user10605163user10605163
2,848624
2,848624
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53354241%2fwhy-my-program-doesnt-read-data-from-the-binary-file-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Will Gladly appreciate each answer ,that each explained ans will provide me a relief .
– Dipesh sapkota
Nov 17 '18 at 18:32
Handy reading: stackoverflow.com/a/42440290/4581301
– user4581301
Nov 17 '18 at 19:30