【问题标题】:How can I send a message to a buffer and print the message with the first three words in reverse?如何将消息发送到缓冲区并用前三个单词反向打印消息?
【发布时间】:2017-06-20 03:15:30
【问题描述】:

我希望将以下消息:“这是要缓冲的消息”打印为:“a is This message to buffer”。我知道我必须使用 awk ,但我不太确定我该怎么做...

代码如下:

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
    FILE *fpo;              //for writing to a pipe

    char buffer[BUFSIZ+1];      //BUFSIZ defined in <stdio.h>



    //Write buffer a message
    sprintf(buffer, "This is a message to buffer\n");  

    fpo = popen ( "od -c", "w" );   //pipe to command "od -c"
                    //od -- output dump, see "man od"
    if ( fpo != NULL ) 
    {
        //send data from buffer to pipe 
        fwrite(buffer, sizeof(char), strlen(buffer), fpo );  
        pclose ( fpo );             //close the pipe
        return 0; 
    }
    return 1;
}

以下是该程序的输出:

luisgeesb@luisgeesb-pc:~/460/lab4$ g++ -o pipe2 pipe2.cpp
luisgeesb@luisgeesb-pc:~/460/lab4$ ./pipe2
0000000   T   h   i   s       i   s       a       m   e   s   s   a   g
0000020   e       t   o       b   u   f   f   e   r  \n
0000034

基本上我想要这样的东西:

luisgeesb@luisgeesb-pc:~/460/lab4$ g++ -o pipe2 pipe2.cpp
luisgeesb@luisgeesb-pc:~/460/lab4$ ./pipe2
0000000   a       i   s       T   h   i   s       m   e   s   s   a   g
0000020   e       t   o       b   u   f   f   e   r  \n
0000034

【问题讨论】:

  • 是否需要使用 awk?否则将文本读入std::vector&lt;std::string&gt;&gt;,在vector的一部分上使用std::reverse,然后再次输出。
  • 这就是我的想法,只是在我将消息写入缓冲区之前反转字符串,但我想知道这是否可以用 AWK 完成。

标签: c++ awk operating-system pipe


【解决方案1】:
$ echo "This is a message to buffer" | awk '{t=$1;$1=$3;$3=t}1'

a is This message to buffer

请注意,反转奇数元素将使中心保持在原位。这就是为什么这里不需要更改第二个字段。

【讨论】:

  • 是的。我完全理解这一点。我认为这对我有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 2013-03-07
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多