正如标题所说,我需要编写一个小程序来读取标准输入的数据,对其进行排序并将其发送到标准输出。该程序应该接受1个参数,告诉它一条记录的长度(以字节为单位)。以下是我的测试方式:
printf 'D\x00C\x00\x00B\x00A' | ./binsort 2 | od -c
以上应该输出类似于:
0000000 \0 A \0 B C \0 D \0
0000010
这是我目前有的代码(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);
}
然后使用 g++ binsort.c -o binsort
进行编译。
上面的代码可以编译,但它没有输出 printf
发送给它的数据。它应该以 2 字节为一组输出,就像 D\0 C\0 \0B \0A
... 但是它没有。
我在考虑使用 qsort
在一个由 malloc/realloc
分配的数组上进行排序。然而,我从未有过这方面的经验,在这个小实用程序上已经苦苦挣扎了几天。有人可以帮忙吗?
P.S. 有人问这是否是作业任务... 不是 - 我公司的开发人员想使用它来调试其项目的输出。