第1个回答 2010-04-23
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define PATH "file path" //自定义单词文件的路径
#define MAXLEN 32 //单词的最大长度
typedef struct Nword
{
struct Nword* next;
char* word;
}*Pword;
void insert(char* nword, Pword list)
{
Pword p;
Pword new_word = (Pword)malloc(sizeof(struct Nword));
new_word->word = (char *)malloc(MAXLEN);
strcpy(new_word->word, nword);
p = list;
while(p->next != NULL)
{
if(strcmp(new_word->word, p->next->word) > 0)
{
p = p->next;
}
else
{
break;
}
}
new_word->next = p->next;
p->next = new_word;
}
int main(void)
{
FILE* fp;
char tmp[MAXLEN];
Pword ptr;
Pword Nhead = (Pword)malloc(sizeof(struct Nword));
ptr = Nhead;
Nhead->next = NULL;
if((fp = fopen(PATH, "r")) == NULL)
return -1;
while(fgets(tmp, sizeof(tmp), fp) != NULL)
{
insert(tmp, Nhead);
}
while(Nhead->next != NULL)
{
printf("%s",Nhead->next->word);
ptr = Nhead->next;
Nhead->next = Nhead->next->next;
free(ptr->word);
free(ptr);
}
free(Nhead);
fclose(fp);
return 0;
}
大概就是这样,能实现你要的要求,可以参考下。有什么不懂可以研究研究
第3个回答 推荐于2017-09-03
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define FILENAME "c:\\a.txt" /*存放单词的文本文件,可以在此修改路径*/
char *readln(FILE *fp) /*从文件fp中读取一行(一个)单词,保存到字符数组中,返回字符数组的地址,返回NULL说明文件读取已经结束*/
{
char *wd=NULL,c;
int n=0;
if ((c=fgetc(fp))!=EOF) {
wd=(char*)malloc(sizeof(char));
if (!wd) return NULL;
*wd=c;
++n;
while ((c=fgetc(fp))!='\n'&&c!=EOF)
{
wd=(char*)realloc(wd,sizeof(char)*++n);
wd[n-1]=c;
}
wd=(char*)realloc(wd,sizeof(char)*++n);
wd[n-1]='\0';
}
return wd;
}
int cmp(const void *a,const void *b) /*根据字母顺序比较两个单词字符串的大小*/
{
int i=0,j=0;
const char *as=*(const char **)a;
const char *bs=*(const char **)b;
while (as[i]&&bs[j])
if (tolower(as[i])==tolower(bs[j])) {
++i;
++j;
}
else break;
return tolower(as[i])-tolower(bs[j]);
}
void freewds(char **a,const int n) /*释放占用的空间*/
{
int i;
for (i = 0; i<n; i++) {
free(a[i]);
}
free(a);
}
int main(void)
{
char **wds=NULL,*line=NULL;
int i,n=0;
FILE *fp=fopen(FILENAME,"r");
if (!fp) {
fprintf(stderr,"FILE NOT FOUND\n");
return -1;
}
while (line=readln(fp),line) /*将文件中的单词读取到wds数组中*/
{
if (!wds) {
wds=(char **)malloc(sizeof(char*));
n=1;
}
else wds=(char **)realloc(wds,sizeof(char*)*(++n));
wds[n-1]=line;
}
fclose(fp); /*关闭文件*/
qsort(wds,n,sizeof(char*),cmp); /*对单词进行排序,不区分大小写*/
for (i = 0; i<n; i++) { /*输出排序后的结果*/
puts(wds[i]);
}
freewds(wds,n);
return 0;
}
//---------------------------------------------------------------------------本回答被提问者采纳