我如何在标准输入中寻找 [英] How do I seek in stdin

查看:46
本文介绍了我如何在标准输入中寻找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我需要帮助.我想从 stdin 读取 16 个字节.我转换成十六进制形式的每个字节.有没有办法可以使用 read() 函数从头开始读取,而不是从第二个字节读取?另外我怎么知道我是否已经阅读了整个stdin?- 这样我就可以循环调用这个函数,直到我读完整个 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

这是我做的一个函数:

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|

这是一个学校项目,所以我不能使用 mallocscanf.如果我得到一些帮助,我会很高兴,并为我不太懂的英语感到抱歉.

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.

推荐答案

stdin 不可查找.您可以读入字节,但不能倒带或快进.EOF (-1) 表示标准输入中的输入结束与常规文件一样,但如果您与用户进行交互式对话,则它是一个更宽松的概念.

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.

基本上标准输入是面向行的,最好使用模式 printf() 提示,从用户输入整行,printf() 结果(如果适用)和另一个提示,从用户读取整行,等等,至少一开始直到你习惯了标准输入编程.

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.

从第二个字节开始就变得容易了.阅读整行,然后在解析时从 i = 1 开始,而不是从 i = 0 开始.

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.

这篇关于我如何在标准输入中寻找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆