0

该函数应该获取一个参数作为文件的指针,并将所有文件放入struct anagram,然后将其写入另一个文件。现在数据只包含a.word,但它也应该包含a.sorted?我已经使用 printf 检查了 a.sorted,它 printf 输出了正确的数据,但为什么它不写入数据文件?即使我增加了 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”数据:在此处输入图像描述

4

1 回答 1

0

fwrite(&a,1,strlen(word)+1,anagramsFile);应该是fwrite(a.sorted,1,strlen(a.sorted)+1,anagramsFile);我假设排序为的声明char sorted[SOME_LEN];

于 2012-11-21T06:46:57.893 回答