我有这个 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/