使用 fwrite 将多个由标记分隔的字符串打印到二进制文件中

print multiple strings separated by tokens into binary file using fwrite

我必须将存储在以令牌分隔的不同变量中的多个字符串保存到二进制文件中,然后读取它。我是用 f​​printf 做的,一切正常(但因为它是 ASCII,所以不是我需要的)我必须用 fwrite 做,但我不知道怎么做。

fprintf(f,"%s|%s|%d|%d|", guessWord, currentWord, wordlength, errors);

分隔单词的标记是 | 我尝试使用 struct 但它要么错了要么我搞砸了

struct savetofile
{
    char sguessWord[20];
    char filler;
    char scurrentWord[20];
    char filler2;
    int swordlength;
    char filler3;
    int serrors;
    char filler4;
};

struct savetofile savetofile_1 = {guessWord,'|',currentWord,'|',wordlength,'|',errors,'|'};
fwrite(&savetofile_1,1,sizeof(savetofile_1),f);

下面是我如何编写 fread 并使用保存的值

                n2 = fread(c2, 1, 50000, f);
                c2[n2] = '[=12=]';
                char *token = strtok(c2, "|");
                char *words[200] = {0};
                int i = 0;
                while(token != NULL)
                {
                    words[i] = malloc(strlen(token)+1);
                    strcpy(words[i],token);
                    token = strtok(NULL, "|");
                    i++;
                }
                strcpy(guessWord, words[0]);
                strcpy(currentWord, words[1]);
                int temp;
                temp = atoi(words[2]);
                wordlength = temp;
                int temp2;
                temp2 = atoi(words[3]);
                errors = temp2;

如您所述,您想将其存储在二进制文件中,下面的代码就是一个示例。这可能不是您的确切答案,但我相信可以作为参考

int main ()
{
    char guessWord[20] = "abcd";
    char currentWord[20] = "qwert";

    FILE *f =NULL;

    struct savetofile savetofile_1 , savetofile_2;

    memset(&savetofile_1,0, sizeof(savetofile_1)); //initializes the memory location 0
    memset(&savetofile_2,0, sizeof(savetofile_2));

    strcpy(savetofile_1.sguessWord,   guessWord );
    strcpy(savetofile_1.scurrentWord,   currentWord );
    savetofile_1.swordlength =20;
    savetofile_1.serrors = 3;
    savetofile_1.filler ='|';
    savetofile_1.filler2 ='|';
    savetofile_1.filler3 ='|';
    savetofile_1.filler4 ='|';

    f = fopen( "file.bin" , "wb" );                 //Creates in binary format, Also note file name *.bin

    if(f != NULL)
    {
        fwrite(&savetofile_1,1,sizeof(savetofile_1),f);
        fclose(f);                                  //Saves the file
    }


    f = fopen( "file.bin" , "rb" );                 //Opens in binary readmode

    if(f != NULL)
    {
        fread(&savetofile_2, sizeof(savetofile_2), 1, f);  //Reading the structure as is
        fclose(f);
    }

    printf(" %s -- %s -- %d -- %d \n", savetofile_2.scurrentWord,savetofile_2.sguessWord,
                            savetofile_2.swordlength, savetofile_2.serrors);

    return 0;
}