I have got a file that contains data for multiple jpegs (along with some garbage), i need to extract binary from this file, filter out the garbage and create jpegs. I know the starting binary sequence of the jpegs.
char buffer[30];
ifstream fin;
fin.open ("FILENAME.raw", ios::in | ios::binary);
while (!fin.eof())
{
fin.read(buffer,30);
cout<<buffer[2]<<endl;
}
fin.close();
Here i am trying to print the file in binary but, when i run this code, alien characters are printed on the screen.
I think problem here was "cout << buffer[2]" which was converting your binary information to charecters. Try int cast before , also you should use a static "unsigned char array"
because binary data can be unsigned .That will work :
unsigned char buffer[ 30 ];
ifstream fin;
fin.open ("FILENAME.raw", ios::in | ios::binary);
while (!fin.eof())
{
fin.read( (char*)( &buffer[0] ), 30 ) ;
cout << (int)buffer[2] << " ";
}
fin.close();
return 0;
Also if you want to traverse the binary why you are just printing buffer[2].
You should double check the binary contents of the file, as your code seems perfectly fine.
Related
I have a binary file, and let's say at byte 11 to byte 14, representing an integer = 100.
Now I want to replace that integer value = 200 instead of the existing one.
How can I do that using C++?
Thanks
T.
Google is your friend. Searching for "C++ binary files" will give you some useful pages, such as: This useful link
In short, you can do something like this:
int main()
{
int x;
streampos pos;
ifstream infile;
infile.open("silly.dat", ios::binary | ios::in);
infile.seekp(243, ios::beg); // move 243 bytes into the file
infile.read(&x, sizeof(x));
pos = infile.tellg();
cout << "The file pointer is now at location " << pos << endl;
infile.seekp(0,ios::end); // seek to the end of the file
infile.seekp(-10, ios::cur); // back up 10 bytes
infile.close();
}
That works for reading. To open a file for output:
ofstream outfile;
outfile.open("junk.dat", ios::binary | ios::out);
Combining those two and adjusting for your specific needs shouldn't be too hard.
I have been experiencing a bug for the past day that I have not been able to solve.
I have my first method which is for saving player data:
bool Player::savePlayerData() {
ofstream writeFile(getName() + ".bin", ios::out | ios::binary | ios::trunc);
string writeData;
writeData = formatEntityData() + "<" + formatLocationData() + "<" + formatInventory();
writeFile.write(writeData.c_str(), writeData.length() + 1);
writeFile.close();
return true;
}
Note: Assume that getName(), formatEntityData(), formatLocationData(), and formatInventory() return strings and are functional.
Then I have my load player data method:
bool Player::loadPlayerData(string name) {
ifstream readFile(name + ".bin", ios::in | ios::binary | ios::_Nocreate);
if (readFile.good() && readFile.is_open()) {
string data;
getline(readFile, data, '\0');
vector<string> str = split(data, '<');
parseEntityData(str.at(0));
parseLocationData(str.at(1));
parseInventory(str.at(2));
readFile.close();
return true;
}
readFile.close();
return false;
}
Note: Assume that parseEntityData(), parseLocationData(), parseInventory() have string param, void returns and are functional
Note: Assume that split(string, char) takes in a string with a delim. char and splits into vector correctly
So, here is what I am trying to accomplish (for purposes of simplicity lets assume getName() return "luke"):
•Create luke.bin
•Save string to luke.bin in binary
•Load data from luke.bin in form of a string
When I run the program is not properly reading the player data. Instead it is returning as if nothing is in the file. What am I doing wrong? Any tips, ideas, or thoughts would be greatly appreciated.
Code on brothers!
Typically when you open a binary file in notepad++ it gives seemingly
random characters
It depends on data. The string "Hell world" is the same in binary or text. Numbers will appear as text if they are text formatted.
Example of text format:
fout << 1234 << std::endl; //saved as "1234"
Example of binary data:
int i = 1234;
fout.write(&i, sizeof(i)); //saved as 2 bytes, big-endian or little endian binary
ios::binary stops translation of new line characters.
When writing to file, put the exact size:
writeFile.write(writeData.c_str(), writeData.length());
When reading the file, getline(fin, data, '\0'); will stop when it reaches zero or end of file. You should use EOF instead of zero. Better yet, use this method:
std::ifstream f(filename, ios::binary);
if (f.good())
{
f.seekg(0, ios::end);
size_t filesize = (size_t)f.tellg();
f.seekg(0);
std::string data(filesize, 0);
f.read(&data[0], filesize);
cout << data << endl;
return true;
}
return false;
I am trying to read a ppm file and store its contents in an array. I am starting off by trying to display it but I can't seem to output anything.
char magic;
ifstream myfile;
myfile.open(file,ios::in | ios::binary);
if (!myfile.is_open())
{
cout<<"Failed to open";
}
myfile.get(magic);
if(myfile) cout <<magic <<"not working";
myfile.close();
The file is opened but I can't read it. I have also tried outputting by using the << operators, but no luck there either.
It's probable that your file is being read, but your variable isn't storing all the values therein. I suggest adding this instead of myfile.get(magic):
char magic;
ifstream myfile;
if (!myfile.open(file, ios::in | ios::binary)
{
cout << "Failed to open" << endl;
}
vector<char> magicNumbers;
while (myfile >> magic)
{
magicNumbers.push_back(magic);
}
myfile.close();
As you can see, you should store all the values in some kind of array, here I used a vector for flexibility. The rest is up to you.
I'm fairly new with C++ and am trying to read and write binary file. I have used the read and write functions to read text from one file and output it to a new file. However the following characters always appear at the end of the created text file "ÌÌ". Is a particular character indicating the end of file being saved in the character buffer?
int main(){
ifstream myfile("example.txt", ios::ate);
ofstream outfile("new.txt");
ifstream::pos_type size;
char buf [1024];
if(myfile.is_open()){
size=myfile.tellg();
cout<<"The file's size is "<<(int) size<<endl;
myfile.seekg(0,ios::beg);
while(!myfile.eof()){
myfile.read(buf, sizeof(buf));
}
outfile.write(buf,size);
}
else
cout<<"Error"<<endl;
myfile.close();
outfile.close();
cin.get();
return 0;
}
Not the only problem with your code (try it on a file bigger than 1024 bytes) but since you are doing binary I/O you need
ifstream myfile("example.txt", ios::ate|ios::binary);
ofstream outfile("new.txt", ios::binary);
This is a beginner question. I am trying to find a string in text file and replace it back to the same file. Following code works fine collecting contents of file into buffer and replace the string . But when i try to keep the data back to same file, it is filled with some junk character. Please let me know what I am doing wrong ?
#include <iostream>
#include <fstream>
using namespace std;
const char *fileName = "Test.dat";
int main () {
// This is where we'll put the stuff we read from file
char buffer[ 100 ];
ifstream finout(fileName, ios_base::in | ios_base::out | ios_base::binary);
if(!finout.is_open())
{
cout << "Can not open file " << endl;
return(1);
}
while (finout.getline(buffer, sizeof(buffer))
{
string g( buffer );
string search = "am";
string replace = "was";
long j;
if ( (j = g.find(str2)) != string::npos)
{
g.replace(g.find(str2), str2.length(), "str");
finout.write((char *) &g, sizeof(g)); //This won't work
}
cout << g << "\n";
finout.close();
return 0;
}
My Test.dat file contain following information:
Hello, How are you?
I am fine.
When you are read/write as a text file, do not open it by ios_base::binary
You put finout.close(); inside your reading loop, so it just work for one line.
When you are reading/writing a file as a text, use text stream methods and operators.
You are trying to read the size of your string with the sizeof() operator.
This wont work, because it is a keyword, that gives you the non-dynamic size of the object or type.
You should use g.size() to access the string size!
But on the first place, you can handle the stream handle your bug:
finout << g;
will do the job.
First, you want to both read and write a file, so use fstream not ifstream.
Second, you have a text file, so don't use ios_base::binary
Third (char*) &g where g is std::string doesn't work, use g.c_str() instead. (simply write
finout << g;
Now you can start thinking of the implmentation...