gpt4 book ai didi

c - 在 C 中以 64 位读取和写入 64 位

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:04 24 4
gpt4 key购买 nike

我有这个 super 简单的代码,我在其中读取 8 个字节的 block (稍后我将在代码中对其进行加密),然后将它们写到一个新文件中。

它运行良好,但最后 8 个字节没有被写入。知道为什么吗?

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

int main()
{
uint64_t data;
FILE *input, *output;

// create output file

output = fopen("output.txt", "w");

// read file
input = fopen("test.txt", "rb");

if(input)
{
while(fread(&data, 8, 1, input) == 1)
{
fwrite(&data, 8, 1, output);
}

size_t amount;
while((amount = fread(&data, 1, 8, input)) > 0)
{
fwrite(&data, 1, amount, output);
}

fclose(input);
fclose(output);
}

return EXIT_SUCCESS;
}

最佳答案

fread(&data, 8, 1, input)

尝试将一个 8 字节的“项目”读入缓冲区,并返回项目数。如果从当前位置到 EOF 还剩不到 8 个字节,则返回 0。

一个可能的解决方案是改为读取 8 个项目 à 1 个字节:

ssize_t amount;
while ((amount = fread(&data, 1, 8, input)) > 0)
{
fwrite(&data, 1, amount, output);
}

然后在 while block 中,您可以检查 amount 是否为 8 或更少,对于您的加密方式。

关于c - 在 C 中以 64 位读取和写入 64 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647735/

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