void save(double *x, int m, char *input) { int i; char *output; FILE *f; output = chgext(input, ".out"); f = fopen(output, "w"); for (i = 0; i < m; i++) { fprintf(f, "%.17e\n", x[i]); } fclose(f); free(output); }
int UpdateCfg(const char *FileName, char *SectionName, char *VarWanted, char *NewData) { FILE *CfgFile; char line[BUFFERSIZE]; char SectionWanted[BUFFERSIZE]; char CurrentSection[BUFFERSIZE]; enum LineTypes linetype; char var[BUFFERSIZE]; char data[BUFFERSIZE]; char TempFileName[FILENAME_MAX]; FILE *NewCfgFile; int Error = 0; int updated = 0; CfgFile = cant((char *)FileName, "r"); strcpy(TempFileName, FileName); chgext(TempFileName, NULL, "tmp"); NewCfgFile = cant(TempFileName, "w"); strcpy(CurrentSection, "[]"); sprintf(SectionWanted, "[%s]", SectionName); while (EOF != ReadLine(CfgFile, line)) { linetype = SectionLine(line, SectionWanted, CurrentSection); switch (linetype) { case InSection: /* In our section, parse it. */ ParseLine(line, var, data); if ((StrEq(var, VarWanted)) && (!updated)) { strncpy(data, NewData, BUFFERSIZE); data[BUFFERSIZE-1] = NUL; updated = 1; } fprintf(NewCfgFile, "%s = %s\n", var, data); break; case EmptyLine: /* Fall Through. Just copy it. */ case CommentLine: /* Fall Through. Just copy it. */ case NotInSection: /* Fall Through. Just copy it. */ case NewSection: /* Fall Through. Just copy it. */ case FoundSection: /* Fall Through. Just copy it. */ fprintf(NewCfgFile, "%s\n", line); break; case LeavingSection: /* Leaving section, may have to add it */ if (!updated) /* Variable wasn't found, we have */ { /* to add it. */ fprintf(NewCfgFile, "%s = %s\n", VarWanted, NewData); updated = 1; } /* ** Now print current line */ fprintf(NewCfgFile, "%s\n", line); break; } } /* ** Our section may not have even been there, in which case we have ** to add both the variable and the section itself. */ if (!updated) { /* We may have hit EOF while still in our section. */ /* If so, we don't need to add the section header. */ if (!StrEq(CurrentSection, SectionWanted)) fprintf(NewCfgFile, "%s\n", SectionWanted); fprintf(NewCfgFile, "%s = %s\n", VarWanted, NewData); } if (ferror(CfgFile)) Error = -1; if (ferror(NewCfgFile)) Error = -1; fclose(CfgFile); fclose(NewCfgFile); if (!Error) { if (remove(FileName)) return -1; if (rename(TempFileName, FileName)) return -1; } return Error; }