JavaProphet
JavaProphet

Reputation: 991

Linux C read single byte?

I'm working in JNA to call C functions, and I'm quite used to the Java read() function which reads a single byte. Is there a way to do this in C without declaring a buffer?

Upvotes: 1

Views: 6593

Answers (4)

Meixner
Meixner

Reputation: 695

Regarding the answers that suggest using read(), it should look like this:

char b;
int r;
while((r=read(fd,&b,1))==-1 && errno==EINTR) {}
if(r==.....

The reason is that in case of delivery of a signal read() gets interrupted and needs to be restarted. If you do not test for EINTR you may face random, hard to find bugs.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881423

You can use getchar() to get a single byte from standard input, or fgetc() to get it from an arbitrary file handle (stream), such as one of:

int ch = getchar();
// Assuming ch >= 0, you have your byte

or:

FILE *in = fopen ("input.txt", "r");
// should check for NULL return
int ch = fgetc (in);
// Assuming ch >= 0, you have your byte

If you have a file descriptor rather than a handle, you can use read() instead, something like:

int fd = open ("input.txt", O_RDONLY, 0); // should check fd for -1
char ch;
ssize_t quant = read (fd, &ch, 1);
// Assuming quant > 0, ch will hold your byte

Upvotes: 0

Chris Stratton
Chris Stratton

Reputation: 40357

That depends if you want to read a stream (ie, a FILE *) or a file descriptor.

For a stream, you have

getc(FILE *stream);

For a file descriptor, you can use a byte variable as a buffer,something like

unsigned char b; //or signed if you prefer
read(fd, &b, 1);

Upvotes: 2

user3528438
user3528438

Reputation: 2817

char oneByte;
int r=read(fd, &oneByte, 1);

Yes, should work.

Upvotes: 7

Related Questions