How to use the Linux cat command to read the contents of a folder. This is a cool trick.

Posted: February 1, 2013. At: 12:20 PM. This was 5 years ago. Post ID: 5310

This is a neat trick that allows you to use cat to view the contents of a directory. This library is loaded before the cat command is executed and modifies its behavior to allow you to use cat to list a directory.

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#define unlikely(x)     __builtin_expect((x),0)
#define min(x,y)    (x<y?x:y)
ssize_t read(int fildes, void *buf, size_t nbyte)
	struct stat statbuf;
	ssize_t r;
	fstat(fildes, &statbuf);
	if (unlikely(S_ISDIR(statbuf.st_mode))) {
		DIR *fdir;
		struct dirent *dent;
		char *dbuf;
		ssize_t bytes;
		fdir = fdopendir(fildes);
		if (!fdir) {
			perror("failed to fdopendir()");
			goto out;
		dbuf = malloc(nbyte);
		if (!dbuf) {
			perror("failed to create buffer");
			goto out;
		memset(dbuf, 0, nbyte);
		bytes = 0;
		do {
			size_t sbytes;
			if ((dent = readdir(fdir)) != NULL) {
				if (strcmp(dent->d_name, ".") == 0
				    || strcmp(dent->d_name, "..") == 0)
				sbytes = strlen(dent->d_name);
				   nbyte, bytes, sbytes); */
				if (bytes + sbytes > nbyte)
					bytes += sbytes;
				sprintf(dbuf, "%s %s", dbuf, dent->d_name);
		} while (dent != NULL);
		r = min(bytes, nbyte);
		strncpy(buf, dbuf, r);
	} else {
		r = __read(fildes, buf, nbyte);
	return r;

Use this command to compile the source and generate an .so file ready for the next step.

john@adeptus-mechanicus ~/Documents $ gcc read.c -shared -fPIC -o

This is the command you execute to display the output. Loading the .so file beforehand with LD_PRELOAD.

john@adeptus-mechanicus ~/Documents $ LD_PRELOAD=./ cat /tmp
 matecorba-john kde-kdm ksocket-kdm CRX_75DAF8CB7768 mc-john .X11-unix gpg-mycPmO .org.chromium.Chromium.Dg3HqG .ICE-unix pulse-PKdhtXMmr18n hsperfdata_john orbit-john .org.chromium.Chromium.S0goZW mintUpdate pluma.john.566659727 ssh-u0IliDldwVqq .X0-lock unity_support_test.0 pulse-qvjohn@adeptus-mechanicus

And now you have listed the contents of a folder with the cat command using a bit of trickery in the process. This could be useful I guess, but you need to load the .so library every time you want this to work. but a very nice trick to show off with for sure.

1 responses to “How to use the Linux cat command to read the contents of a folder. This is a cool trick.

Leave a Reply