代码之家  ›  专栏  ›  技术社区  ›  David 天宇 Wong

在C中读写64位乘64位

  •  0
  • David 天宇 Wong  · 技术社区  · 11 年前

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

    它工作得很好,但最后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;
    }
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   Martin R    11 年前
    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块中,您可以检查 amount 为您的 加密方法。