[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: help with recovering inode



Andrew Morton wrote:
> 
> The attached program may help.

Doh.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_BYTES 256

void usage()
{
	fprintf(stderr, "usage: bgrep filename bytes\n");
	exit(1);
}

#define S_LOOK	1
#define S_SEEN	2

void doit(char *filename, unsigned nbytes, unsigned char *bytes)
{
	FILE *f = stdin;
	long offset = 0;
	unsigned idx = 0;
	int state = 0;

	if (strcmp(filename, "-") != 0) {
		f = fopen(filename, "r");
		if (f == 0) {
			perror("fopen");
			exit(1);
		}
	}

	state = S_LOOK;
	for ( ; ; ) {
		int c = fgetc(f);

		if (c == EOF)
			break;

		switch (state) {
		case S_LOOK:
			if (c == bytes[0]) {
				offset = ftell(f);
				idx = 0;
				state = S_SEEN;
			} else {
				break;
			}
			/* Fall through */
		case S_SEEN:
			if (c == bytes[idx]) {
				idx++;
				if (idx == nbytes) {
					printf("%s: match at offset %lu[0x%lx]\n",
						filename, offset, offset);
					fseek(f, offset + 1, SEEK_SET);
					state = S_LOOK;
				}
			} else {
				state = S_LOOK;
				fseek(f, offset + 1, SEEK_SET);
			}
			break;
		}
	}
	if (f != stdin)
		fclose(f);
}

int main(int argc, char *argv[])
{
	char *filename = 0;
	unsigned char bytes[MAX_BYTES];
	unsigned nbytes = 0;
	int arg;

	for (arg = 1; arg < argc; arg++) {
		char *cp = argv[arg];
		if (filename == 0) {
			filename = cp;
		} else {
			if (nbytes >= MAX_BYTES)
				usage();
			bytes[nbytes++] = strtoul(cp, NULL, 16);
		}
	}

	if (filename == 0 || nbytes == 0)
		usage();

	doit(filename, nbytes, bytes);
	exit(0);
}

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]