将操作缓冲区写入新文件

Write manipulated buffer to new file

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

 /*-----------------------------------------
 *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: %s\n",  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: %s\n", outputFile);
                fwrite(buffer, sizeof(unsigned char), lSize, pFile);
                fclose (pFile);
        }
        return 1;
}

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

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