As the title says, I need to write a small program to read data from standard input, sort it, and send it to standard output. The program should take 1 argument that tells it how long is one record (in bytes). Here’s how I test it:
printf 'D\x00C\x00\x00B\x00A' | ./binsort 2 | od -c
The above should output something like:
0000000 \0 A \0 B C \0 D \0 0000010
Here’s what I have so far (binsort.c):
#include <stdio.h> #include <stdlib.h> #include <limits.h> using namespace std; void print_usage() { printf('%s\n', 'Usage: '); } int compare (const void * a, const void * b) // the compare function for qsort... might need some work { return ( *(int*)a - *(int*)b ); } int main(int argc, char *argv[]) { if (argc != 2 || stdin == NULL) // check for argument and piped input { print_usage(); exit(EXIT_FAILURE); } int entry_size = atoi(argv[1]); if (entry_size <= 0 || entry_size >= INT_MAX) // check for valid range of entry size { print_usage(); exit(EXIT_FAILURE); } char *input = new char[entry_size]; // to hold single record while (fgets(input, entry_size, stdin) != NULL) { printf('%s', input); // output single record we just read } exit(EXIT_SUCCESS); }
Then compile with g++ binsort.c -o binsort.
The above compiles but doesn’t output the data that printf sent to it. It should output it in 2-byte chunks… like D\0 C\0 \0B \0A… but it doesn’t.
I’m thinking of using qsort to do the sorting on a malloc/realloc-allocated array. However, I never had experience with these, in effect banging my head on this little utility for a few days. Anyone can help?
P.S. People asked if this is a homework assignment… It’s not – developers at my company want to use this to debug output of their project.
Don’t use
scanf()andprintf(). Those are supposed to be used with text data. Since you’re dealing with binary data, you instead want to use the lower-levelfread()andfwrite()functions. Since you don’t know how much total data there is, you’ll have to use a dynamic data structure (such as a resizeable array) to store the input. You can’t process the data on-line — you have to read it all in, sort it, then write it back out. Your sort function is also wrong — you’re only comparing the first 4 bytes of each record, which is wrong if the record size is anything other than 4 bytes. Usememcmp()instead.This should work: