【发布时间】:2009-12-06 03:56:38
【问题描述】:
我对此很陌生,所以我尝试编译第 119 页(第 5.11 节)上的 main 及其依赖项。我设法用这个得到了一个干净的构建:
#include <stdio.h>
#include <string.h>
#define ALLOCSIZE 10000
#define MAXLINES 5000
#define MAXLEN 1000
int getline(char *, int);
char *alloc(int);
char *lineptr[MAXLINES];
int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);
void qsort(void *lineptr[], int left, int right,
int (*comp)(void *, void *));
int numcmp(char *, char *);
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
/* getline: read a line, return length */
int getline(char *line, int max)
{
if (fgets(line, max, stdin) == NULL)
return 0;
else
return strlen(line);
}
char *alloc(int n)
{
if (allocbuf + ALLOCSIZE - allocp >= n) {
allocp += n;
return allocp - n;
} else
return 0;
}
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];
nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || (p = alloc(len)) == NULL)
return -1;
else {
line[len-1] = '\0'; /* delete newline */
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}
/* writelines: write output lines */
void writelines(char *lineptr[], int nlines)
{
int i;
for (i = 0; i < nlines; i++)
printf("%s\n", lineptr[i]);
}
void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
/* qsort: sort v[left]...v[right] into increasing order */
void qsort(void *v[], int left, int right,
int (*comp)(void *, void *))
{
int i, last;
void swap(void *v[], int, int);
if (left >= right)
right;
swap(v, left, (left + right)/2);
last = left;
for(i = left+1; i <= right; i++)
if((*comp)(v[i], v[left]) < 0)
swap(v, ++last, 1);
swap(v, left, last);
qsort(v, left, last-1, comp);
qsort(v, last+1, right, comp);
}
#include <stdlib.h>
/* numcmp: compare s1 and s2 numerically */
int numcmp(char *s1, char *s2)
{
double v1, v2;
v1 = atof(s1);
v2 = atof(s2);
if (v1 < v2)
return -1;
else if (v1 > v2)
return 1;
else
return 0;
}
/* strcmp01: return <0 if s<t , 0 if s==t, >0 if s>t */
int strcmp01(char *s, char *t)
{
for( ; *s == *t; s++, t++)
if(*s == '\0')
return 0;
return *s - *t;
}
/* sort input lines */
main(int argc, char *argv[])
{
int nlines;
int numeric = 0;
if (argc > 1 && strcmp01(argv[1], "-n") == 0)
numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void **) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp01));
writelines(lineptr, nlines);
return 0;
}
else {
printf("input too big to sort\n");
return 1;
}
}
但是当我在 DOS 窗口中运行它时(值得一提的是 Win 7),光标命令提示符接受多行键输入,并且...。究竟是什么?在我输入几行希腊语后,什么也没有发生。我只是 Ctrl C 退出它,然后我回到命令提示符。
或者,我将几行内容组合成一个 test.txt 文件并尝试运行
[DIR\]mybuild.exe <[DIR\]test.txt
这只会引发错误(出现一个 Win 7 对话框,显示“mybuild.exe 已停止工作”)。它确实找到了 test.txt 文件;它只是“停止工作”。
如何才能成功运行此程序? (我只是在尝试,以前从未见过它在任何地方运行过。)谢谢大家的帮助。
【问题讨论】:
标签: c