这个函数应该获取一个参数作为文件的指针,并将所有文件放入struct anagram
,然后将其写入另一个文件。现在,每个数据都有很多空间。charCompare 工作正常,因为我制作了一个测试文件来测试它。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
#define SIZE 80
//struct
struct anagram {
char word[SIZE];
char sorted[SIZE];
};
void buildDB ( const char *const dbFilename ){
FILE *dict, *anagramsFile;
struct anagram a;
//check if dict and anagram.data are open
errno=0;
dict= fopen(dbFilename, "r");
if(errno!=0) {
perror(dbFilename);
exit(1);
}
errno=0;
anagramsFile = fopen(anagramDB,"wb");
char word[SIZE];
char *pos;
int i=0;
while(fgets(word, SIZE, dict) !=NULL){
//get ripe of the 'n'
pos=strchr(word, 'n');
*pos = ' ';
//lowercase word
int j=0;
while (word[j]){
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), sizeof(char), charCompare);
strncpy(a.sorted,word,sizeof(word));
fwrite(&a,1,sizeof(struct word),anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
数据: 第10名 第1名 第2名
可能的原因是传递给qsort()
的大小参数。从链接的参考页面qsort()
:
size- 数组中每个元素的大小(以字节为单位)
因此大小参数应该是1
的,保证是sizeof(char)
的,而不是sizeof(char*)
可能是4
或8
的。发布的代码错误地通知qsort()
word
指向比实际数组大4
(或8
)倍的数组,qsort()
将访问它不应该访问的内存。更改为:
qsort(word,strlen(word), 1, charCompare);
另一个可能的原因是此行导致的缓冲区溢出:
strncpy(&a.sorted[i],word,sizeof(word));
i
在while
循环的每次迭代中都会递增,但始终在写入sizeof(word)
。不会发布SIZE
和BUFSIZ
的值,但即使它们相等,strncpy()
也会在第一次迭代后超出a.sorted
的范围写入。
其他要点:
fgets()
不保证读取换行符,因此在取消引用之前检查strchr()
的返回值。tolower()
返回小写字符,则不会更改其参数。- 为什么要读入临时缓冲区(
word
)并复制?只需直接阅读struct
成员即可。