我必须将存储在不同变量中的多个字符串(由令牌分隔)保存到二进制文件,然后再读取它。我用fprintf做到了,一切正常(但是由于是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] = '\0';
                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;
}

关于c - 使用fwrite将多个由 token 分隔的字符串打印到二进制文件中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47733275/

10-14 11:06