- int rc = 0;
-
- if (pfxlen <= 1)
- errno = EINVAL;
- else {
- int infd = open(filename, O_RDWR | O_CREAT | O_EXLOCK, fmode);
-
- if (infd != -1) {
- FILE *infp = fdopen(infd, "r+");
-
- if (infp == NULL)
- close(infd);
- else {
- int outfd;
- char file[MAXPATHLEN];
-
- strcpy(file, filename);
- strcat(file, ".new");
- outfd = open(file, O_RDWR | O_CREAT | O_TRUNC | O_EXLOCK, fmode);
- if (outfd != -1) {
- FILE *outfp = fdopen(outfd, "w+");
-
- if (outfp == NULL)
- close(outfd);
- else {
- int updated = UPD_CREATE;
- char line[2048];
-
- while (fgets(line, sizeof(line), infp) != NULL) {
- char *p = strchr(line, '\n');
-
- if (p == NULL) { /* Line too long */
- int ch;
-
- fputs(line, outfp);
- while ((ch = fgetc(infp)) != EOF) {
- fputc(ch, outfp);
- if (ch == '\n')
- break;
- }
- continue;
- }
- if (*line != '#' && *line != '\n') {
- if (!updated && strncmp(line, prefix, pfxlen) == 0) {
- updated = updmode == UPD_REPLACE ? UPD_REPLACE : UPD_DELETE;
-
- /*
- * Only actually write changes if updating
- */
- if (updmode == UPD_REPLACE)
- strcpy(line, newline);
- else if (updmode == UPD_DELETE)
- continue;
- }
- }
- fputs(line, outfp);
- }
-
- /*
- * Now, we need to decide what to do: If we are in
- * update mode, and no record was updated, then error If
- * we are in insert mode, and record already exists,
- * then error
- */
- if (updmode != updated)
- errno = (updmode == UPD_CREATE) ? EEXIST : ENOENT;
- else {
-
- /*
- * If adding a new record, append it to the end
- */
- if (updmode == UPD_CREATE)
- fputs(newline, outfp);
-
- /*
- * Flush the file and check for the result
- */
- rc = fflush(outfp) != EOF;
- if (rc) {
-
- /*
- * Copy data back into the
- * original file and truncate
- */
- rewind(infp);
- rewind(outfp);
- while (fgets(line, sizeof(line), outfp) != NULL)
- fputs(line, infp);