用C语言读写64位乘64位 [英] Reading and writing 64bits by 64 bits in C

查看:252
本文介绍了用C语言读写64位乘64位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this super simple code where I read blocks of 8 bytes (I will encrypt them later in the code) and then write them down in a new file.

它工作得很好,但对于最后8个字节没有写入.知道为什么吗?

It works well but for the last 8 bytes which don't get written. Any idea why?

#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.

tries to read one "item" with 8 bytes into the buffer, and returns the number of items. If less than 8 bytes are left from the current position to EOF, it returns 0.

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

One possible solution would be to read 8 items à 1 byte instead:

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

然后在while块中,您可以检查amount是否为8或更小 加密方法.

Inside the while-block you can then check if amount is 8 or less, for your encryption method.

这篇关于用C语言读写64位乘64位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆