Skip to content

Instantly share code, notes, and snippets.

@fknaopen
Created April 27, 2013 16:15
Show Gist options
  • Save fknaopen/5473632 to your computer and use it in GitHub Desktop.
Save fknaopen/5473632 to your computer and use it in GitHub Desktop.
リングバッファを逆向きに読みたい時のおぼえがき。 主にログファイル用リングバッファを新しい順に読むときに使うかな・・・
/*
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment