Last active
December 22, 2016 00:29
-
-
Save drbr/e95a6cfd2b5ee50416ad to your computer and use it in GitHub Desktop.
C program to sort items given as input arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdlib.h" | |
#include "stdio.h" | |
#include "string.h" | |
/* | |
* Returns a string containing each argument separated by a newline. | |
*/ | |
char* parse_args(int argc, char** argv) { | |
int char_count = 0; | |
for (int i = 1; i < argc; i++) { | |
char_count += (strlen(argv[i]) + 1); | |
} | |
char* format = (char*) malloc(char_count * sizeof(char)); | |
char* format_index = format; | |
for (int i = 1; i < argc; i++) { | |
char* str = argv[i]; | |
strcpy(format_index, str); | |
format_index += strlen(str); | |
if (i < argc - 1) { | |
*(format_index++) = '\n'; | |
} else { | |
*format_index = '\0'; | |
} | |
} | |
return format; | |
} | |
/* | |
* Takes the input arguments and sorts them, removing duplicates, | |
* printing the output to the screen. | |
*/ | |
int main(int argc, char** argv) { | |
char* input = parse_args(argc, argv); | |
char* command_format = "echo \"%s\" | sort -u"; | |
char command[strlen(input) + strlen(command_format) - 2]; | |
sprintf(command, command_format, input); | |
return system(command); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this because I hadn't done anything in C for a while and I wanted to see if I still remembered how to work with pointers and arrays. The actual sorting is on lines 34-38, and isn't the point of this code.