c fwrite() 写入仅包含一个结构变量的文件?

标签 c

该函数应该获取一个参数作为文件的指针,并将所有文件放入 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” 数据:enter image description here

最佳答案

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/

相关文章:

c - C 中的 float 除法表现得很奇怪?

c - 如何将消息(在 C 中)从一个线程发送到另一个线程?

c - 关于 C 和 eclipse - scanf

c - C中的阻塞/非阻塞定时器

C - 使用 strtok 将字符串数组拆分为字符数组

android - 是否可以在 SO 库中公开 C API 以访问 Android JAVA 方法?

c - 使用 phtreads 从 C 中的多个线程读取和写入不同位置的数组是否安全?

c - 数组分离---C

c - 如何在我的程序的多个文件中共享结构?

C链表和指针