문제

I just dont understand what is wrong with my code, The goal is to encrypt one file using other file as a key using bitwise xor. It works, the problem is that the while is executed only one time and thats not enough. The if statement in the while is in case the key is shorter than the input file. fd_in,fd_key and fd_out are the file descriptors.

while ((numOfBytes = read(fd_in, buf, 4096))!=0){
    numOfBytes_key=read(fd_key, buf_key, numOfBytes);
    if (numOfBytes>numOfBytes_key){
        lseek(fd_in, -(numOfBytes - numOfBytes_key), SEEK_CUR);
        lseek(fd_key, 0, SEEK_SET);
    }
    for (i = 0; i < numOfBytes_key; i++){
        buf_out[i] = buf[i] ^ buf_key[i];
    }
    write(fd_out, buf_out, numOfBytes_key); 
}

올바른 솔루션이 없습니다

다른 팁

I guess that read functions can mess things up, since reading from empty, non existing ect file will return -1.Thus, rest of computations will fall. Try to avoid that by including if firective:

while ((numOfBytes = read(fd_in, buf, 4096))!=0)
{
    numOfBytes_key=read(fd_key, buf_key, numOfBytes);
    if (numOfBytes>numOfBytes_key && (numOfBytes >= 0) &&(numOfBytes_key >= 0 ))
    {
        lseek(fd_in, -(numOfBytes - numOfBytes_key), SEEK_CUR);
        lseek(fd_key, 0, SEEK_SET);
    }
    for (i = 0; i < numOfBytes_key; i++){
        buf_out[i] = buf[i] ^ buf_key[i];
    }
    write(fd_out, buf_out, numOfBytes_key); 
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top