What is a portable way to writie a struct to a file in C?

前端 未结 3 733
你的背包
你的背包 2020-12-16 15:39

I need to serialize a C struct to a file in a portable way, so that I can read the file on other machines and can be guaranteed that I will get the same thing t

3条回答
  •  囚心锁ツ
    2020-12-16 16:08

    Write one function for output. Use sprintf to print an ascii representation of each field to the file, one field per line.

    Write one function for input. Use fgets to load each line from the file. Use scanf to convert to binary, directly into the field in your structure.

    If you plan on doing this with a lot of different structures, consider adding a header to each file, which identifies what kind of structure it represents.

提交回复
热议问题