该函数应该获取一个参数作为文件的指针,并将所有文件放入 struct anagram 中,然后将其写入另一个文件。现在数据只包含 a.word,但它也应该包含 a.sorted 吗?我已经使用 printf 检查了 a.sorted 它打印出正确的数据,但为什么它不写入数据文件? 即使我增加 frwite 的数量,它仍然无法得到 a.sorted
#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 = '\0';
strncpy(a.word,word,sizeof(word));
//lowercase word
int j=0;
while (word[j])
{
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), 1, charCompare);
strncpy(a.sorted,word,sizeof(word));
//printf(a);
fwrite(&a,1,strlen(word)+1,anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
它假设包含带有 a.sorted 的数据,例如“10th 01ht” 数据:
最佳答案
fwrite(&a,1,strlen(word)+1,anagramsFile);
应该是 fwrite(a.sorted,1,strlen(a.sorted)+1,anagramsFile );
我假设排序的声明为 charsorted[SOME_LEN];
关于c fwrite() 写入仅包含一个结构变量的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13487195/