结构体存储到文件里,fread读取错误,总是乱码

Python019

结构体存储到文件里,fread读取错误,总是乱码,第1张

你写完文件后,没有关闭文件,导致后面读文件的时候无法打开文件。

我修改了下,可以正常读取了

#include <stdlib.h>

#include <malloc.h>

typedef struct

{

char *CardCode

char *Name

char *Contact

char *Password

char AccountType

double MoneyCount

}*AccountRecord, AccountInfo

int AccountInfoWrite(AccountInfo Record)

{

FILE *fp

char *FileName="12345678.Bq"

//FileName = stringjoin(Record.CardCode, ".Bq")

if (fopen_s(&fp,FileName, "w")!=0)

{

printf("文件已新建! \n")

return 1

}

if (fwrite(&Record, sizeof(AccountInfo)+1, 1, fp) == 1)

{

printf("账户信息写入成功! \n")

fclose(fp)

return 0

}

else

{

printf("账户信息写入失败! \n")

return 1

}

return 0

}

void read()

{

AccountInfo buffer

FILE *fp

int errorcode = fopen_s(&fp, "12345678.Bq", "rb")

if (0 != errorcode)

{

printf("open file error:%d!\n",errorcode)

return

}

fread(&buffer, sizeof(AccountInfo), 1, fp)

fclose(fp)

printf("%s \n", buffer.Name)

}

int main()

{

AccountRecord a = (AccountRecord)malloc(sizeof(AccountRecord))

a->Name = "aassasasa"

a->CardCode = "12345678"

a->Contact = "110"

a->Password = "112233"

a->AccountType = 'a'

a->MoneyCount = 111.00

AccountInfoWrite(*a)

read()

return 0

}

下面这三部,可以逐一试一下。

1、Rstudio相关设置要改成UTF-8。位置在:1、Tools → Global Options → Default text encoding ;2、File → Save with encoding

2、数据文本要更改为UTF-8编码,工具notepad++,操作:Encoding → Convert to UTF-8,保存,参考

3、读取数据是,在read.csv或其他读取函数中,添加读取文件编码的参数 fileEncoding = "UTF8