Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I seek in stdin

Tags:

c

stdin

Hello guys I need a help. I want to read from stdin by 16 bytes. Every byte I convert into hexadecimal form. Is there a way I can use read() function to read NOT from the beginning, but for example from the second byte? Also how can I know if I have read the whole stdin? - This way I could call this function in a cycle until I have read the whole stdin

This is a function I made:

void getHexLine()
{

  int n = 16;
  char buffer[n];
  read(STDIN_FILENO, buffer, n);
  buffer[n]='\0';
  //printf("%08x", 0); hex number of first byte on line - not working yet
  putchar(' ');
  putchar(' ');
  //converting every byte into hexadecimal
  for (int i = 0;i < 16;i++ )
  {
    printf("%x", buffer[i]);
    putchar(' ');
    if (i == 7 || i == 15)
        putchar(' ');


  }
  printf("|%s|\n", buffer);
} 

The output should be like this but with an option to start from second byte for example.

[vcurda@localhost proj1]$ echo "Hello, world! This is my program." | ./proj1
48 65 6c 6c 6f 2c 20 77  6f 72 6c 64 21 20 54 68  |Hello, world! Th|
69 73 20 69 73 20 6d 79  20 70 72 6f 67 72 61 6d  |is is my program|

This is a school project so I cant use malloc, scanf and <string.h>. I would be really glad if I get some help and sorry for my not very understandable english.

like image 497
Vojta Čurda Avatar asked Oct 15 '16 19:10

Vojta Čurda


People also ask

Can you seek stdin?

stdin is not seekable. You can read bytes in, but you can't rewind or fast forwards.

How do I pass Ein to stdin?

It should be sent by the user. So is it that only the user can invoke EOF in stdin by pressing Ctrl + Z ? Yes, you can set the EOF indicator for stdin with a special key combination you can input in the console, for linux console that is Ctrl + D and for windows it's Ctrl + Z .

What happens if you close stdin?

close(fileno(stdin)) causes any further attempts at input from stdin , after the current buffer has been depleted, to fail with EBADF , but only until you open another file, in which case that file will become fd #0 and bad things will happen.


1 Answers

stdin is not seekable. You can read bytes in, but you can't rewind or fast forwards. EOF (-1) means end of input in stdin as with a regular file, but it's a bit of a looser concept if you are conducting an interactive dialogue with the user.

Basically stdin is line oriented, and it's best to use the pattern printf() prompt, enter whole line from user, printf() results if applicable and another prompt, read in whole line from user, and so on, at least at first until you get used to programming stdin.

To start from the second byte then becomes easy. Read in the whole line, then start from i = 1 instead of i = 0 as you parse it.

like image 134
Malcolm McLean Avatar answered Oct 02 '22 23:10

Malcolm McLean