简体   繁体   English

从文件中读取 1 个字节

[英]Read 1 byte from file

I need to read a single byte from a file.我需要从文件中读取一个字节。 Normally when reading, I use a char array as the buffer.通常在阅读时,我使用一个字符数组作为缓冲区。 However, I need to be able to perform binary operations with byte, which can't be done with a char array.但是,我需要能够使用字节执行二进制操作,而使用字符数组则无法做到这一点。 Here's what I've got:这是我所拥有的:

read(file, buffer, 1);

I've tried making buffer both a char and an int, but both give me warnings that it expects a void * argument.我已经尝试将缓冲区同时设为 char 和 int,但两者都警告我它需要一个 void * 参数。 But of course, that doesn't allow for binary operations like &.但当然,这不允许像 & 这样的二元运算。

How can I store buffer such that I can perform binary operations on it?如何存储缓冲区以便我可以对其执行二进制操作?

You could use the function int fgetc (FILE *fp) .您可以使用函数int fgetc (FILE *fp) The return value will be an int value from 0 to 255 or EOF .返回值将是一个从 0 到 255 或EOFint值。

Binary operation can be performed on char data type with unsigned .可以对带有unsigned char数据类型执行二元运算。 Even if its an array binary operation can be done to the single element of the array.即使它的数组二进制操作可以对数组的单个元素进行。

for your reference.供你参考。

ssize_t read(int fd, void *buf, size_t count);

buffer has to be address of the character or character array , in your single char is sufficient.缓冲区必须是charactercharacter array地址,在您的单个char就足够了。 If you want to use array use the element array[0] and perform operation on that.如果要使用数组,请使用元素array[0]并对其执行操作。

As mentioned in the comments above正如上面的评论中提到的

unsigned char c; 
read(file, &c, 1);

你可以读入一个 char 数组,因为你(据说)知道如何做,然后对该数组的第一个元素执行二进制操作。

typedef unsigned char uint8_t; /* Not necessary if you are using C99, i.e. <stdint.h>. */

uint8_t buffer[BUF_SIZE] = {0};
    .
    .
    .
if (fread(buffer, sizeof(buffer[0]), 1, file) == 1)
{
    buffer[0] ^= 0xFFu; /* Or any other bit-wise operation. */
}

Refer -参考 -
1. https://linux.die.net/man/3/fread 1. https://linux.die.net/man/3/fread
2. http://en.cppreference.com/w/c/types/integer 2. http://en.cppreference.com/w/c/types/integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM