我需要知道如何读取具有不同行中的值的文件,并将其与内存中的值进行比较,以获得哪一行具有更好的分数,如果内存中的值最好,则将这些值插入到文件中(文件同时以读和写方式打开,因为这部分代码可以同时从多个 fork() 运行):
if (PuntuacioEquip(jugadors)>MaxPuntuacio && CostEquip(jugadors)<PresupostFitxatges)
{
//Compare with file
int fd, n;
TBestEquip info;
fd = open("best_teams.txt", O_RDONLY);
if (fd<0) panic("open");
while ((n=read(fd, &info, sizeof(info))) == sizeof(info)) {
//printf(cad,"equip %lld, puntuacio %d\n", info.Equip, info.Puntuacio);
//write(1,cad,strlen(cad));
if (info.Puntuacio>PuntuacioEquip(jugadors))
{
fd = open("best_teams.txt", O_WRDONLY|O_TRUNC|O_CREAT,0600);
if (fd<0) panic("open");
sprintf(cad,"%s Cost: %d Points: %d. %s\n", CostEquip(jugadors), PuntuacioEquip(jugadors));
write(fd,cad,strlen(cad));
}
}
// We have a new partial optimal team.
MaxPuntuacio=PuntuacioEquip(jugadors);
memcpy(MillorEquip,&jugadors,sizeof(TJugadorsEquip));
sprintf(cad,"%s Cost: %d Points: %d. %s\n", color_green, CostEquip(jugadors), PuntuacioEquip(jugadors), end_color);
write(1,cad,strlen(cad));
}
感谢任何帮助。
问候,
迭代文件的最佳方法是使用函数
getline()
。这是它的使用示例,取自这篇文章,我建议您阅读。
char const* const fileName = "best_teams.txt" ; //
FILE* file = fopen(fileName, "r"); /* should check the result */
if (file != NULL) {
char line[256];
while (getline(line, sizeof(line), file)) { // Each iteration, a line will be stored in string `line`
// Do what you want to do
} // Exits when arrives at the end of the file
else puts("Error while opening file\n");
按照评论中的建议,您可以使用
fopen("best_teams.txt", "w")
“w”表示写入模式,在fopen文档中描述如下:
创建一个空文件用于写入。如果已存在同名文件,则其内容将被删除,并且该文件被视为新的空文件。
另一种解决方案是以读写模式打开,并且只更改您想要的值,但可能会更复杂。