Ημερήσια αρχεία: 19 Νοεμβρίου 2011


C/C++: How to round up a number

#include 
intergerVariable = ceil (floatVariable);

To compile with math.h library you MUST include the -lm flag.

gcc -lm main.c


C/C++: Capture stdout from a system() command

	FILE *results;
	int queen;
	if (!(results = popen("./precosat -f nqueens.cnf | tail -n +2 | head -n -1 | tr -d v | tr ' ' '\n' | grep -v '^$' | grep ^[0-9]", "r"))) {
		cout << "Unable to Execute Precosat" << endl << "./precosat -f nqueens.cnf | tail -n +2 | head -n -1 | tr -d v | tr ' ' '\n' | grep -v '^$' | grep ^[0-9]" << endl;
		exit(1);
	}
	for (i = 0; i < queens; i++) {
		fscanf(results,"%d",&queen);
		cout << "Queen #" << i+1 << " goes to [" << ((queen%queens)?(queen%queens):queens) << "]" << endl;
	}
	pclose(results);

Above, you will find an example that was used to extract data from the PrecoSAT SAT Solver in order to solve the N-Queens problem. It returns all positive variables, one per line.

You can see that after the call to popen, it creates a pointer to a file stream that can be used as a regular file to read the data from the called process.


Bash: grep: A couple of usefull applications

(How) to delete all empty lines from a file:

cat someFile | grep -v '^$'

(How) to get all numbers that have no sign in front of them (all positive numbers, from a file where on each line there is one number only):

cat someFile | grep ^[0-9]

(How) to extract all negative numbers (from a file where on each line there is one number only):
You can of course replace the minus ‘-‘ character with any other you want to use as a starting character for a line.

cat someFile | grep ^-