如何将消息发送到缓冲区并反向打印前三个单词的消息

How can I send a message to a buffer and print the message with the first three words in reverse?

本文关键字:消息 三个 单词 打印 缓冲区      更新时间:2023-10-16

我希望将以下消息:"这是要缓冲的消息"打印为:"a 是要缓冲的消息"。我知道我必须使用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 buffern");  
    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
$ echo "This is a message to buffer" | awk '{t=$1;$1=$3;$3=t}1'
a is This message to buffer

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