|
-
May 20th, 2009, 06:01 PM
#1
Using Multithreading to encrypt a file
My problem sounds like this:
I have to create a program that encrypts a file by taking each byte and increment it.
The problem is that the program should use multithreading to do the actual encrypting. The number of threads is variable, the user enters them in a Edit Control, and those “x” number of threads, simultaneously must encrypt the file.
What I’ve done so far is that I opened the file in binary mode and encrypt it by incrementing each byte in the file. So far so good, but now I can’t figure out how to create those threads and how should they encrypt the file simultaneously … a little help would be awesome.
Here is the code I done so far: when the user pushes the Ok button (the file has been selected by the user in a previous step), the selected file is encrypted
Code:
void CEncryptorView::OnBnClickedOk()
{
CString strControlText;
CWnd* pWnd = GetDlgItem(IDC_FILE);
pWnd->GetWindowText(_T(strControlText));
char buf[255];
//open the selected file for encryption
ifstream fp_in(strControlText, ios_base::binary | ios_base::in);
unsigned int cntr = 0; //defining a controll variable;
if(!fp_in)
{
++cntr;
MessageBox("The selected file couldn't be open for reading");
}
ofstream fp_out("temp.txt", ios_base::binary | ios_base::out);
if(!fp_out)
{
++cntr;
MessageBox("\tThe temp file couldn't be created \n(check you access privileges for default destination!)");
}
//encrypting the file, taking each byte in the file and increment it
if ( fp_in && fp_out )
{
char ch;
while ( fp_in.get ( ch ) )
fp_out.put ( ++ch );
}
else
++cntr;
fp_in.close();
fp_in.clear();
fp_out.close();
fp_out.clear();
//copying (replacing) the encrypted temp file into the original file, and deleting the tempoarary one
ifstream fs_in("temp.txt", ios_base::binary | ios_base::in);
if(!fs_in)
{
++cntr;
MessageBox("An error occured and the encryption failed");
}
ofstream fs_out(strControlText, ios_base::binary | ios_base::out);
if(!fs_out)
{
++cntr;
MessageBox("An error occured and the encryption failed");
}
if ( fs_in && fs_out )
{
char ch;
while ( fs_in.get ( ch ) )
fs_out.put ( ch );
}
else
++cntr;
fs_in.close();
fs_in.clear();
fs_out.close();
fs_out.clear();
//delete the temp file
CString fileToDelete("temp.txt");
if(remove(fileToDelete) == 0 && cntr == 0)
MessageBox("The file has ben encrypted successfully");
else
MessageBox("An error occured and the encryption failed");
}
Thank you!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|