简体   繁体   English

c fwrite()只向struct变量之一写入数据吗?

[英]c fwrite() writing data only right one of the struct variable?

This function is supposed to get a parameter as the pointer of a file and put all file into the struct anagram, then write it to another file. 该函数应该获取一个参数作为文件的指针,并将所有文件放入struct anagram,然后将其写入另一个文件。 Right now the data only contains a.word, but it suppose to containst a.sorted too? 现在数据仅包含a.word,但它也想包含a.sorted吗?

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"


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));

        fwrite(&a,1,sizeof(word),anagramsFile);

        i++;
    }
    fclose(dict);
    fclose(anagramsFile);

}

data: 数据:

在此处输入图片说明

char word[SIZE];
...
fwrite(&a,1,sizeof(word),anagramsFile);

sizeof(word) returns the full size of the buffer, so you're writing the full length of the buffer each time. sizeof(word)返回缓冲区的完整大小,因此您每次都在写缓冲区的完整长度。 You'll want to use strlen() or similar to only write the part of the buffer you're actually using. 您将要使用strlen()或类似方法仅写入您实际使用的部分缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM