简体   繁体   English

使用fscanf读取序列化数据

[英]read serialized data using fscanf

I have a array of C struct, and I'm serializing it to a file, and I need to retrive that data to memory again. 我有一个C结构数组,我将它序列化为一个文件,我需要再次将该数据检索到内存。

movie list[50]; //array

typedef struct{
    int code;
    int year;
    float price;
    char title[50];
    char director[30];
    char description[255];
} movie;

serialized data exemple 序列化数据例子

1|1990|9.900000|Hello world|Foo bar baz|lorem ipsum bla bla|
34|1994|4.900000|lorem ipsum|lorem ipsum|lorem ipsum|
23|1993|5.100000|lorem ipsum|lorem ipsum|lorem ipsum|
.
.
.

To serialize I just traverse the array and fprintf every property to a line. 为了序列化我只是遍历数组并将每个属性fprintf转换为一行。

But to read the data the obvious doesn't work 但要阅读数据显然不起作用

while( fscanf("%d|%d|%f|%s|%s|%s|",&list[i].code, &list[i].year, ...)!= EOF){
i++;
...
}

This does NOT work 这不起作用

sscanf(input,"%[ˆ|]|%[ˆ|]|%[ˆ|]",string1,string2,string3);

The mistake was so subtle that I took almost 3 hours to find the answer to my problem: 错误是如此微妙,我花了将近3个小时来找到问题的答案:

sscanf(input,"%[^|]|%[^|]|%[^|]",string1,string2,string3);

The problem is probably because I'm using US International English layout keyboard on my US macbook. 问题可能是因为我在我的美国macbook上使用US International English布局键盘。

This cause the ^ key (Shift-6) to appear as a accent ˆ until you press a consonant it turns to â ê î ô û or if you press spacebar it turn the accent to a character, and I never realized that these two ˆ^ was different. 这导致^键(Shift键6),显示为一个口音ˆ你按下一个辅音则转为â ê î ô û或者如果你按下空格键它打开口音角色,我从来没有意识到这ˆ^是不同的。

I'm not sure about english, but at least in portuguese the ^ ins not a character is called a circumflex accent, is used on consonants â ê î ô û to represent different pronunciation. 我不确定英语,但至少在葡萄牙语中,不是一个字符被称为旋风口音,用于辅音toû来代表不同的发音。

So if you're using a American keyboard you will have to press Shift+6 and then Spacebar to make a ^ 因此,如果您使用美式键盘,则必须按Shift + 6然后按空格键才能生成^

"the obvious doesn't work"... that's when you read the function's manpage :-(. “明显不起作用”......当你阅读函数的手册页时: - (。

The %s format doesn't stop reading a string when it hits a | %s格式在到达|时不会停止读取字符串 ... if you look at the fscanf documentation you'll see there's another format instruction allowing you to control which characters are read into the string vs. terminating the conversion.... ...如果你查看fscanf文档,你会看到另一种格式指令,允许你控制哪些字符被读入字符串而不是终止转换....

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

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