Этот код
bytesread = read(fd, &temp, 1);
считывает один байт в первый байт unsigned int
, который почти наверняка больше, чем один байт. Поэтому, когда ваши данные, которые вы читаете, попадают в значение int
, зависит от вашей системы.
Если вы собираетесь читать один байт, обычно гораздо проще просто использовать [unsigned] char
, чтобы вы всегда знаю, где это закончится. Чтобы преобразовать unsigned char
в int
, вы можете просто назначить его:
int main()
{
int fd = open("inputs.txt", O_RDONLY);
if(fd == -1)
{
// perror() will tell you **WHAT** error occurred
perror( "open()" );
exit(-1);
}
// this is now an unsigned char
unsigned char temp;
// read() returns ssize_t, not int
ssize_t bytesread = read( fd, &temp, sizeof( temp ) );
if ( bytesread != sizeof( temp ) )
{
perror( "read()" );
close( fd );
exit( -1 );
}
close( fd );
// there are a lot of ways to do this
printf( "unsigned int value: %u\n", ( unsigned int ) temp );
// this is another way - it prints the hex value
printf( "hex value: %hhx\n", temp );
// this prints the char value:
printf( "char value: '%c'\n", temp;
// this converts that unsigned char into an int:
int intvalue = temp;
// yes, it's that simple.
printf( "int value: %d\n", intvalue );
return 0;
}
Обратите внимание, что результаты могут отличаться, если sizeof( int ) == sizeof( unsigned char )
. В этом случае могут быть значения unsigned char
, которые нельзя представить в виде значения int
.