文本文件操作_单词的排序
在当前目录有文件“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测试通过