Skip to content

Commit

Permalink
Write output to a temp file and rename it afterwards.
Browse files Browse the repository at this point in the history
Fixes #20
  • Loading branch information
robryk committed Jan 17, 2017
1 parent 01ea6b6 commit c9f5384
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions guetzli/guetzli.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
* limitations under the License.
*/

#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "gflags/gflags.h"
#include "png.h"
#include "guetzli/processor.h"
Expand Down Expand Up @@ -196,12 +197,30 @@ int main(int argc, char** argv) {
return 1;
}

FILE* fout = fopen(argv[2], "wb");
if (!fout) {
fprintf(stderr, "Can't open output file for writing\n");
if (access(argv[2], W_OK) != 0 && errno != ENOENT) {
// This is only relevant if the output directory is sticky, but /tmp often
// is.
fprintf(stderr, "Can't overwrite the output file\n");
return 1;
}

FILE* fout_tmp;
char fout_tmp_name[1024];
{
snprintf(fout_tmp_name, sizeof(fout_tmp_name), "%sXXXXXX", argv[2]);
fout_tmp_name[sizeof(fout_tmp_name) - 1] = '\0';
int fd = mkstemp(fout_tmp_name);
if (fd < 0) {
fprintf(stderr, "Can't create a file in the output directory\n");
return 1;
}
fout_tmp = fdopen(fd, "w");
if (!fout_tmp) {
perror("fdopen");
return 1;
}
}

std::string in_data = ReadFileOrDie(fin);
std::string out_data;

Expand Down Expand Up @@ -237,6 +256,11 @@ int main(int argc, char** argv) {
}
}

WriteFileOrDie(fout, out_data);
WriteFileOrDie(fout_tmp, out_data);
if (rename(fout_tmp_name, argv[2]) < 0) {
fprintf(stderr, "Can't overwrite the output file\n");
return 1;
}

return 0;
}

0 comments on commit c9f5384

Please sign in to comment.