Hi,
I have function which will replace (or create) an file with the contents of another stream.
The stream could be anything. The replacement is done safely.
The code might have multiple potential problems. Can anyone help me to find out.
Thanks in advanceCode:#include <errno.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> int do_replace(const char *file, int stream, int cnt) { char *env = getenv("CDIR"); if (env == NULL) env = "."; char *rpath = realpath(env, NULL); if (rpath == NULL || strlen(rpath) >= PATH_MAX) { free(rpath); return -1; } char tname[PATH_MAX+32]; snprintf(tname, sizeof tname, "%s/safetemp_XXXXXX", rpath); free(rpath); int ofd = mkstemp(tname); if (ofd == -1) return -2; char rbuf[1024], *pbuf, bad = 0; while (!bad) { int r = read(stream, pbuf=rbuf, sizeof rbuf); if (r == 0) break; else if (r < 0 && EINTR == errno) continue; else if (r < 0) bad = 1; else while (r > 0 && !bad) { int w = write(ofd, pbuf, r); if (w > 0) { r -= w; pbuf += w; } else bad = 1; } } if (close(ofd)) bad = 1; if (close(stream)) bad = 1; if (cnt == 1) sleep(100); if (!bad && rename(tname, file)) bad = 1; if (bad) { unlink(tname); return -3; } return 0; }




Reply With Quote