Reputation: 111
I am trying to read first 121 bytes from a text file onto a structure.
Here is my code.
#include <fstream.h>
#include <iostream.h>
#include <conio.h>
#include <sys/stat.h>
int main()
{
struct
{
char map[121];
} map_data;
struct stat results;
fstream myfile("input.txt", ios::in);
myfile.read((char *)&map_data,121);
if(!myfile)
{
cout<<"Unable to open the file";
}
if(!myfile.read((char *)&map_data,121))
{
cout<<"Second error occurred";
}
myfile.close();
cout<<"\n Here are the read contents of size "<<sizeof(map_data)<<"\n";
fstream outfile("output.txt", ios::out);
for(int i=0;i<121;i++)
{
cout<<map_data.map[i]<<" ";
}
outfile.write((char *)&map_data,121);
outfile.close();
stat("input.txt",&results);
cout<<"\n Size of input.txt "<<results.st_size;
stat("output.txt",&results);
cout<<"\n Size of output.txt "<<results.st_size;
getch();
}
The problem is that the above code skips the first character of the file i.e the h of the hello. Its cout and the output.txt file both show this thing.
Can somebody guide me how to solve this?
Upvotes: 1
Views: 1694
Reputation: 47794
I followed the guide courses.cs.vt.edu/cs2604/fall02/binio.html
The example shows two different ways to read a file notice a ... in between example.
It also says // Same effect as above
So just comment out either of the two read call.
fstream myfile("input.txt", ios::in);
//myfile.read((char *)&map_data,121);
if(!myfile.read((char *)&map_data,121))
{
cout<<"Second error occurred";
}
Upvotes: 1
Reputation: 86525
I'm semi surprised that only the first character is missing. It ought to be missing 121 chars.
fstream myfile("input.txt", ios::in);
// you read 121 bytes here...
myfile.read((char *)&map_data,121);
if (!myfile) {
cout<<"Unable to open the file";
}
// and then do it again here, before you ever look at `map_data`.
if (!myfile.read((char *)&map_data,121)) {
cout<<"Second error occurred";
}
Upvotes: 0