gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:37:48 24 4
gpt4 key购买 nike

我必须将存储在由标记分隔的不同变量中的多个字符串保存到二进制文件,然后读取它。我用 fprintf 做到了,一切正常(但因为它是 ASCII,所以不是我需要的),我必须用 fwrite 做到这一点,但我不知道如何。

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

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

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 将由标记分隔的多个字符串打印到二进制文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47733275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com