【发布时间】:2017-11-29 22:07:20
【问题描述】:
我的代码存在严重问题。我正在通过以下方式保存一些数据:
void savetofile()
{
fprintf(savefile, "%d\n", run); // here are 1 or 2 characters
fprintf(savefile, "%d\n", gender); // 1 character
fprintf(savefile, "%s\n", name); // here is string, max 20 characters
fprintf(savefile, "%d\n", points1); // between 1 and 3 characters
fprintf(savefile, "%d\n", points2); // between 1 and 3 characters
}
保存后如何阅读?我可以以某种方式具体说明:
fscanf(savefile, "%d", &gender);
要特别阅读第 2 行?
也许当我将数据保存到文件时:
void savetofile()
{
fprintf(savefile, "%d ", run); // here are 1 or 2 characters
fprintf(savefile, "%d ", gender); // 1 character
fprintf(savefile, "%s ", name); // here is string, max 20 characters
fprintf(savefile, "%d ", points1); // between 1 and 3 characters
fprintf(savefile, "%d ", points2); // between 1 and 3 characters
}
会更容易阅读吗?
【问题讨论】:
-
如果您在文件中打印了 5 行,您应该从该文件中读取这 5 行,使用与写入每一行时相同的格式。
-
1) 使用第一个
void savetofile()2) 发布您的输出示例。 3) 发布变量的定义。 -
gender真的是int(或者您打算将其存储为int),还是char?考虑使用fgets()从文件中读取输入行,并使用sscanf()解析每一行。 -
提示:写名字的时候,记得有些名字里面有空格。因此,请使用
fprintf(savefile, "<%s>\n", name);之类的标记来编写。然后阅读更容易检测到格式错误的数据。 -
您的主要问题是指定文件格式。完成后,对解析器进行编码是常见的做法,您会发现很多关于解析的书籍(和编译:大多数编译器书籍都在第一部分研究解析技术)