Reading bmp file for steganography - c++

I am trying to read a bmp file in C++(Turbo). But i m not able to print binary stream.
I want to encode txt file into it and decrypt it.
How can i do this. I read that bmp file header is of 54 byte. But how and where should i append txt file in bmp file. ?
I know only Turbo C++, so it would be helpfull for me if u provide solution or suggestion related to topic for the same.
int main()
{
ifstream fr; //reads
ofstream fw; // wrrites to file
char c;
int random;
clrscr();
char file[2][100]={"s.bmp","s.txt"};
fr.open(file[0],ios::binary);//file name, mode of open, here input mode i.e. read only
if(!fr)
cout<<"File can not be opened.";
fw.open(file[1],ios::app);//file will be appended
if(!fw)
cout<<"File can not be opened";
while(!fr)
cout<<fr.get(); // error should be here. but not able to find out what error is it
fr.close();
fw.close();
getch();
}
This code is running fine when i pass txt file in binary mode
EDIT :
while(!fr)
cout<<fr.get();
I am not able to see binary data in console
this was working fine for text when i was passing character parameter in fr.get(c)

I think you question is allready answered:
Print an int in binary representation using C
convert your char to an int and you are done (at least for the output part)

With steganography, what little I know about it, you're not "appending" text. You're making subtle changes to the pixels (shading, etc..) to hide something that's not visually obvious, but should be able to be reverse-decrypted by examining the pixels. Should not have anything to do with the header.
So anyway, the point of my otherwise non-helpful answer is to encourage you go to and learn about the topic which you seek answers, so that you can design your solution, and THEN come and ask for specifics about implementation.

You need to modify the bit pattern, not append any text to the file.
One simple example :
Read the Bitmap Content (after header), and sacrifice a bit from each of the byte to hold your content

If on Windows, recode to use CreateFile and see what the real error is. If on Linux, ditto for open(2). Once you have debugged the problem you can probably shift back to iostreams.

Related

Read and write image data C++

I've just started learning C++, and I'm working on a program that is supposed to grab an image from the hard disk and then save it as another name. The original image should still remain. I've got it work with text files, because with those I can just do like this:
ifstream fin("C:\\test.txt");
ofstream fout("C:\\new.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout.put(ch);
}
fin.close();
fout.close();
}
But I suppose that it's not like this with images. Do I have to install a lib or something like that to get it work? Or can I "just" use the included libraries? I know I'm not really an expert of C++ so please tell me if I'm totally wrong.
I hope someone can and want to help me! Thanks in advance!
Btw, the image is a .png format.
You can use the std streams but use the ios::binary argument when you open the stream. It's well documented and there is several examples around the internet
You are apparently using MS Windows: Windows distinguishes between "text" and "binary" files by different handling of line separators. For a binary file, you do not want it to translate \n\r to \n on reading. To prevent it, using the ios::binary mode when opening the file, as #Emil tells you.
BTW, you do not have to use \\ in paths under windows. Just use forward slashes:
ifstream fin("C:/test.txt");
This worked even back in WWII using MS-DOS.
If the goal is just to copy a file then CopyFile is probably better choice than doing it manually.
#include <Windows.h>
// ...
BOOL const copySuccess = CopyFile("source.png", "dest.png", failIfExists);
// TODO: handle errors.
If using Windows API is not an option, then copying a file one char at a time like you have done is very inefficient way of doing this. As others have noted, you need to open files as binary to avoid I/O messing with line endings. A simpler and more efficient way than one char at a time is this:
#include <fstream>
// ...
std::ifstream fin("source.png", std::ios::binary);
std::ofstream fout("dest.png", std::ios::binary);
// TODO: handle errors.
fout << fin.rdbuf();

Writing an integer into an ifstream C++

Okay, so, I can now read from .txt files as variables, but how do I write the integers once changed back into my text file?
Example:
xps.open ("xp.txt"); //Text file is loaded and applied to ifstream 'xps'
int xp;
xps >> xp; //xps is applied to integer xp
xp += 50; //xp has 50 added to it's value
and then I want the value of xp to be written (overwriting the previous number) into xp.txt, so how would I do this?
It's inefficient to write and overwrite the same value. Just wait until you know what value you want to write to the file, and write it.
I presume you mean ofstream rather than ifstream since you are writing to the file in this question. If you absolutely have to go back in the file then you need to call seekp(). In order to do this you need to remember the point in the file to start writing to which you can get by calling tellp(). So, if you want my advice, try not to have to re-write the value.
You need to open the text file for both reading and writing; declare xps as an fstream and then you can just do
xps << xp

C++ filestream problem

I'm making a simple game in C++ and I want the highest score at the end of the game to be written in a text file. I'm using fstream to first read the last saved highscore and compare it to the new highscore. The output in the text file looks like this (0НН) and it shouldn't. I'm realy frustrated with this.
Here's a part of my code.
double score_num=0;
fstream datafile("score.pon"); //Declaration of variables
...
if(SPEED>score_num)
{
score_num=SPEED;
}
//getting the score
...
datafile<<score_num; //Writing it to the file
#include <iostream>
#include <fstream>
using namespace std;
#define SPEED 12
int main()
{
double score_num=0;
ofstream datafile("score.pon"); //Declaration of variables
if(SPEED>score_num)
{
score_num=SPEED;
}
//getting the score
datafile<<score_num; //Writing it to the file
return 0;
}
Replaced fstream by ofstream works like a charm. Perhaps you should show more code? Also, closing the file is good habit:
datafile.flush();
datafile.close();
I'll leave errorhandling to you
Hacky solution - open the file as an ifstream, read existing value, close it, adjust score, open file as an ofstream, write score, close it. Alternatively, investigate the use of the seekp() function, and write the score as a binary value, not as text.
My best guess as to why the original was failing is that when you read the last character from a file, the EOF bit is set. In this state, all read & write operations fail. You can write to a file stream that's reached its end by calling clear first.
// the following doesn't truncate file, or handle other error conditions.
if (datafile.eof()) {
datafile.clear();
}
datafile.seekp(0, std::ios_base::beg);
datafile << score_num;
However, this won't solve all your problems. If you write less to the file than its current length (e.g. the old high score was "1.5" and the new high score is "2"), part of the old data will still be present at the end of the file. As long as scores never have a fractional part (in which case you should probably be using an integer type, such as unsigned long), you won't notice the bug, since a < b ⇒ len(a) ≤ len(b). To handle this properly, you'll need to use unapersson's recommended approaches (which will either truncate the file or always write the same amount of data to the file), or use a different I/O library (such as your platform's C library or boost) which provide a way to truncate files (such as the POSIX ftruncate).

binary file encryption problem

i'm having a problem while encrypting some data in the file. i'm using simple xor for that.
lets say i have this struct:
struct MyFile{
char fileName[128];
int account;
float balance;};
saving this as a binary file is working properly but when i use xor to encrypt the filename in the struct and save the struct to hd then reading the struct and decrypting the filename is not showing the characters correctly. i'm using this simple function for the encryption/decryption purpose.
static void Codec(const char *key,int keySize,char* in,char *result,int length)
{
for(int i=0;i<length;i++)
result[i]=in[i]^key[i%keySize];
}
Note that when i encrypt the filename and directly decrypt it in memory the result is right. what am i missing like why is it being changed when saved on the hard disk. please reply asap and tnx in advance...
First, determine whether the data is actually being altered when it is written to the disk. Have your program print out the string in these four places:
Before encrypting it
After encrypting it but before writing it to the disk
After reading it from the disk but before decrypting it
After decrypting it
Are the results from #2 and #3 the same? If so, then the file is not being changed during the transfer to disk and back.
If #2 and #3 are different, try writing the unencrypted string to disk and reading it back out. Does this work successfully?
Write only a single such structure to a file and examine the contents of the file in a hex editor. What does the file look like while it is on the disk?
Post your write-to-disk and read-from-disk code as well, part of the problem may lie there.
You must open the file in binary mode. If you use C I/O (like I normally do) this means
FILE *input_file = fopen(input_file_name, "rb");
FILE *output_file = fopen(output_file_name, "wb");
If instead you've been tricked into using C++ streams this means
std::ifstream input_file(input_file_name, ios::in | ios::binary);
std::ofstream output_file(output_file_name, ios::out | ios::binary);
Note that you need to open the files in binary mode ("rb"/"wb" instead of "r"/"w" for fopen). Windows C implementations in particular have problems regarding \n<->\r\n conversion.
It is also a good idea to use unsigned chars for arithmetic and bitwise operations; anything but 8-bit two's complement signed chars might cause trouble (which, granted, most implementations use and might not cause any trouble with symmetric XOR encryption, but it's still good to be careful.)

Read Unicode files C++

I have a simple question to ask. I have a UTF 16 text file to read wich starts with FFFE. What are the C++ tools to deal with this kind of file? I just want to read it, filter some lines, and display the result.
It looks simple, but I just have experience in work with plain ascci files and I'm in the hurry. I'm using VS C++, but I'm not want to work with managed C++.
Regards
Here a put a very simple example
wifstream file;
file.open("C:\\appLog.txt", ios::in);
wchar_t buffer[2048];
file.seekg(2);
file.getline(buffer, bSize-1);
wprintf(L"%s\n", buffer);
file.close();
You can use fgetws, which reads 16-bit characters. Your file is in little-endian,byte order. Since x86 machines are also little-endian you should be able to handle the file without much trouble. When you want to do output, use fwprintf.
Also, I agree more information could be useful. For instance, you may be using a library that abstracts away some of this.
Since you are in the hurry, use ifstream in binary mode and do your job. I had the same problems with you and this saved my day. (it is not a recommended solution, of course, its just a hack)
ifstream file;
file.open("k:/test.txt", ifstream::in|ifstream::binary);
wchar_t buffer[2048];
file.seekg(2);
file.read((char*)buffer, line_length);
wprintf(L"%s\n", buffer);
file.close();
For what it's worth, I think I've read you have to use a Microsoft function which allows you to specfiy the encoding.
http://msdn.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx
The FFFE is just the initial BOM (byte order mark). Just read from the file like you normally do, but into a wide char buffer.