LoginSignup
0
1

More than 5 years have passed since last update.

C:リングバッファを逆向きに読み出す

Last updated at Posted at 2018-11-04

リングバッファを逆向きに読みたい時のcode

主にログファイル用リングバッファを新しい順に読むときに使うかな・・・

(「index = (rbuf.head + MAX_BUF - i) % MAX_BUF;」が書きたいことの全てですが。)

/*
 * read reverse ring-buffer
 */
#include <stdio.h>
#include <string.h>

#define MAX_BUF (16)

struct ring_t {
    int  head;          // now data
    int  tail;          // next target data
    char data[MAX_BUF];
};

void p_data(char *data){
    int i;
    for (i=0; i<MAX_BUF; i++){
        printf("%c ", data[i]);
    }
    printf("\n");
}

main(){
    struct ring_t rbuf;
    char data[MAX_BUF];

    int i, index;

    // set ring-buffer
    memset(&rbuf, 0, sizeof(rbuf));
    memset(rbuf.data, '-', sizeof(rbuf.data));
    for (i=0; i<20; i++){
        rbuf.data[rbuf.tail]='A'+i;  // set test data
        rbuf.head=rbuf.tail;
        rbuf.tail=(i+1) % MAX_BUF;
    }
    printf("rbuf.head=%d\n   ", rbuf.head);
    p_data(rbuf.data);               // test

    // data copy (read ring-buffer)
    memset(data, 0, sizeof(data));
    for (i=0; i<MAX_BUF; i++){
        index = (rbuf.head + i) % MAX_BUF;
        data[i] = rbuf.data[index];
    }
    printf("f: ");
    p_data(data);                    // test

    // data copy (read reverse ring-buffer)
    memset(data, 0, sizeof(data));
    for (i=0; i<MAX_BUF; i++){
        index = (rbuf.head + MAX_BUF - i) % MAX_BUF;
        data[i] = rbuf.data[index];
    }
    printf("r: ");
    p_data(data);                    // test
}

実行結果

$ a.out
rbuf.head=3
   Q R S T E F G H I J K L M N O P
f: T E F G H I J K L M N O P Q R S
r: T S R Q P O N M L K J I H G F E
0
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1