You need to work on your use of streams.
First, you declare c as an array of 502 chars, then you attempt to read a file into c using only 1 >>. If your lucky that will get the first char from the file into the first index (0) of the array c.
A good way to read from files is either 1 char at a time checking for eof each iteration of a loop, or to read line by line using a string. You still have to check for eof each iteration
Here is a function i wrote to do XOR (de)/(en)cryption to a file. It uses iostream.h stdio.h and string.h
Check out the code challenge of this issue of the c journal
http://www.cprogramming.com/codej/issue2.html
It uses FILE *'s instead of streams, you should be able to change it becuase it is commented
Code:
int XOR(char * filename, unsigned long key)
{
char * outfilename = NULL;
int len = strlen(filename);
unsigned char buffer;
if( (filename[len-4] == '.') && (filename[len-3] == 'e') && (filename[len-2] == 'n') && (filename[len-1] == 'c') )
{
// our input file is encoded then we will create a file without the .end extension
outfilename = new char[len+1]; //make room for the name+\0
strcpy(outfilename,filename); //copy the string name
outfilename[len-4] = '\0'; //put the \0 before the .enc extension to cut it off
}
else
{
outfilename = new char[len+5]; //make room for the name + .enc + \0
strcpy(outfilename,filename); //copy the file name
strncat(outfilename,".enc",4); //add the .enc extension
}
input = fopen(filename,"rb");
if( input == NULL)
{
cout << "Error opening file " << filename << endl;
delete [] outfilename; //free the memory before leaving
outfilename = NULL;
return 1;
}
output = fopen(outfilename,"wb");
if( output == NULL )
{
cout << "Error creating output file " << outfilename << endl;
delete [] outfilename; //free the mem before leaving
outfilename = NULL;
return 1;
}
while( ! feof(input) )
{
//get some data
if( fread(&buffer,sizeof(unsigned char),1,input) != 1 )
{
//if we didnt get any data, but we are not at the eof, then an error has occured
if( ! feof(input) )
{
delete [] outfilename;
outfilename = NULL;
fclose(input);
fclose(output);
return 1;
}
}
else
{
//xor that data
buffer ^= key;
//write some data
fwrite(&buffer,sizeof(unsigned char),1,output);
}
}
//close the files and free that memory
fclose(input);
fclose(output);
delete [] outfilename;
return 0;
}