gpt4 book ai didi

c - 为什么unsigned char变量包含EOF?

转载 作者:行者123 更新时间:2023-11-30 16:45:48 24 4
gpt4 key购买 nike

我开发了一种加密算法,它从 .txt 文件中逐字符获取文本并对其进行加密,然后将其写回另一个 .txt 文件。问题是当我读取加密文件时,像箭头这样的字符充当 EOF,并且我的循环在原始 EOF 之前终止。这是我的代码:

static void ECB_ENCRYPTION(void)
{
uint8_t i = 0, j = 0, c, buf1[16]


uint8_t plain_text[16];

// File pointers for file operations.
FILE *f, *f1;


// Encrypts the file [plaintext.txt].
f = fopen("plaintext.txt", "r");
f1 = fopen("ciphertext.txt", "w");
while(1)
{
i = 0;
while(i < 16)
{
c = getc(f);
if(feof(f))
{
break;
}
else
{
plain_text[i] = c;
++i;
}
}

if(i != 16)
{
while(i < 16)
{
plain_text[i] = ' ';
++i;
}
}

// Encrypts plain text.
AES128_ENCRYPT(plain_text, buf1);

i = 0;
while(i < 16)
{
putc(buf1[i], f1);
++i;
}

if(feof(f))
break;

}

fclose(f);
fclose(f1);
}

static void ECB_DECRYPTION(void)
{

uint8_t i = 0, j = 0, c, buf1[16];

uint8_t cipher_text[16];

// File pointers for file operations.
FILE *f, *f1;

// Encrypts the file [plaintext.txt].
f = fopen("ciphertext.txt", "r");
f1 = fopen("decryptedtext.txt", "w");
while(1)
{
i = 0;
while(i < 16)
{
c = getc(f);
if(feof(f))
{
break;
}
else
{
cipher_text[i] = c;
++i;
}
}

if(feof(f))
break;

// Decrypts cipher text.
AES128_DECRYPT(cipher_text, buf1);

i = 0;
while(i < 16)
{
putc(buf1[i], f1);
++i;
}

}

fclose(f);
fclose(f1);
}

最佳答案

使用uint8_t c而不是int c混淆了真正的问题:以二进制模式与文本模式打开文件。 @Klas Lindbäck

int c会更好。还是OP使用uint8_t; c = getc(f); if(feof(f)) 几乎正确。发生读取错误时失败。

static void ECB_DECRYPTION(void) {
uint8_t cipher_text[16];
uint8_t buf1[16];

FILE *f = fopen("ciphertext.txt", "rb"); // add 'b'
assert(f);
FILE *f1 = fopen("decryptedtext.txt", "wb"); // add 'b'
assert(f1);
while(1)
{
int c;
for (unsigned i=0; i<16; i++) {
c = getc(f);
if (c == EOF) break;
cipher_text[i] = (uint8_t) c;
}

if(c == EOF) break; // exit loop on end-of-file or input error

AES128_DECRYPT(cipher_text, buf1);

for (unsigned i=0; i<16; i++) {
putc(buf1[i], f1);
}
}

fclose(f);
fclose(f1);
}

关于c - 为什么unsigned char变量包含EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com