c-将操作过的缓冲区写入新文件



我的程序试图通过将文件写入缓冲区、操作缓冲区数据,然后将缓冲区写入新的输出文件来解密文件的数据。目前这个程序不操作缓冲区内的数据,它只是按原样将缓冲区数据写入输出文件。将操作过的数据从缓冲区写入新文件的正确方法是什么?

/*-----------------------------------------
*swaps the nibbles of a byte
*/
unsigned char nibbleSwap(unsigned char byte){
return( (byte & 0x0f) << 4 | (byte & 0xf0) >>4);
}
/*-----------------------------------------
* swaps the bits of given data
*/
unsigned char bitSwap(unsigned char byte){
unsigned char b = nibbleSwap(byte);
b= (b & 0xcc) >>2 | (b & 0x33) <<2;
b= (b & 0xaa) >>1 | (b & 0x55) <<1;
return(b);
}
int main(int argc, char**argv){
FILE * pFile;
char * outputFile;
unsigned char * buffer;
long lSize;
size_t result;
//gets filename from cmd line
printf("Author: Torin Costales n");
for (int x=1; x<argc; x++)
printf("Input File: %sn",  argv[x]);
pFile = fopen(argv[1], "rb");
if(pFile == NULL){
printf("OPEN ERROR");
return -1;
}
//file size
fseek (pFile, 0, SEEK_END);
lSize= ftell(pFile);
rewind (pFile);
//buffer allocation
buffer = (unsigned char*) malloc (sizeof(unsigned char)*lSize);
if(buffer == NULL) {
printf("MEM ERROR");
return -1;
}

//read data from file into the buffer
result =fread(buffer, sizeof(unsigned char), lSize, pFile);
if(result != lSize){
printf("Read error");
return -1;
}
//decrypt data, odd bytes nibbles are swapped, even bytes have bits reversed
for(int x =0; x < sizeof(buffer); x++){
if(x % 2 == 1){
nibbleSwap(buffer[x]);
}
else
bitSwap(buffer[x]);
}
//make output file
if(argc >=2){
outputFile = argv[1];
char appendix[] = ".d";
strncat(outputFile, appendix, 2);
pFile= fopen(outputFile, "wb");
printf("Output File: %sn", outputFile);
fwrite(buffer, sizeof(unsigned char), lSize, pFile);
fclose (pFile);
}
return 1;
}

尝试将nibbleSwapbitSwap调用的结果分配给buffer[x],即将第二个循环更改为:

for(int x =0; x < sizeof(buffer); x++){
if(x % 2 == 1){
buffer[x] = nibbleSwap(buffer[x]);
}
else
buffer[x] = bitSwap(buffer[x]);
}

最新更新