c语言 文件操作 对文件里的字符串按首字母排序,文本文件操作_单纯词的排序...

文本文件操作_单词的排序

在当前目录有文件“case1.in”,文件里存放有多个(总个数不超过10000个)英文单词(每个英文单词不会超过10个字文字符),每行一个,单词未排序。现要求,将文件中的所有单词按字典顺序排序,然后将排序好的单词写入新建的文件answer.txt中(注:文件存放于当前目录)。请完成程序,实现该功能,(注意,填空题,请不要使用return 0结束,否则会影响评判而判错) (如case1.in文件中原内容如下)

hello

bye

yes

(程序执行后,在文件answer.txt中内容如下)

bye

hello

yes

#include "stdio.h"

#include "string.h"

main()

{

_______________________

}

------解决思路----------------------

#include 

#include 

static int  count;

static char words[10000][10 + 1];

int

wordcmp(const void *v1, const void *v2)

{

const char *p1;

const char *p2;

p1 = (const char *)v1;

p2 = (const char *)v2;

return strcmp(p1, p2);

}

int

main(int argc, char *argv[])

{

int    i;

FILE  *fp;

size_t len;

char   buf[80 + 1];

fp = fopen("case1.in", "rb");

count = 0;

while (fgets(buf, sizeof(buf) , fp)) {

len = strlen(buf);

if (len > 0) {

buf[len - 1] = '\0';

}

strcpy(words[count], buf);

count++;

}

fclose(fp);

qsort(words, count, sizeof(words[0]), &wordcmp);

for (i = 0; i 

printf("%s\n", words[i]);

}

return 0;

}

------解决思路----------------------

#include "stdio.h"

#include "string.h"

#include "stdlib.h"

int strCmp(const void *str1, const void *str2)//排序

{

return strcmp((char *)str1, (char *)str2);

}

void main()

{

FILE *fpInFile, *fpOutFile;

char str[10000][16]={'\0'};

int i = 0, iStrLen = 0;

fpInFile = fopen("case1.in","r+");

if(fpInFile == NULL)

{

printf("Error: Open file failed!\n");

return;

}

printf("Open file succeed!\n");

while(!feof(fpInFile))

{

if(fgets(str[i],16,fpInFile)!= NULL)

printf("%s",str[i]);

i++;

iStrLen++;

}

fclose(fpInFile);

printf("iStrLen:%d\n",iStrLen);

qsort(str, iStrLen -1, sizeof(char)*16, strCmp);

fpOutFile = fopen("answer.txt","w+");

for(i=0; i

{

printf("sort:%s",str[i]);

fputs(str[i],fpOutFile);

}

fclose(fpOutFile);

}

VC测试通过

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值