Dave's Brain

Browse - programming tips - shuffle file

Date: 2008feb14
Language: C++

Q.  How do I output a file in random order like the shuf command?

A.  This code does the trick.  Its compact and efficient.

#include <stdio.h>
#include <errno.h>
#include <string>
#include <vector>
#include <algorithm>

typedef std::vector<std::string>	LINES;

static bool readfile(const char *file, LINES &lines)
{
	FILE		*f;
	char		buf[5*1024+1];
	char		*p;

	if ((f = fopen(file, "r")) == NULL)
	{
		fprintf(stderr, "Could not open %s because %s\n", file, strerror(errno));
   		return false;
	}

	for (;;)
	{
		if (fgets(buf, sizeof(buf), f) == NULL) break;
		if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; // Remove newline
		lines.push_back(buf);
	}

	fclose(f);
	return true;
}

static bool shuffle(const char *file)
{
	LINES		lines;
	LINES::iterator	it;

	if (!readfile(file, lines)) return false;

	srand(time(NULL));
	random_shuffle(lines.begin(), lines.end());

	for (it = lines.begin(); it != lines.end(); it++)
	{
		printf("%s\n", it->c_str());
	}

	return true;
}

main()
{
	shuffle("myfile.txt");
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.