@@ -370,6 +370,42 @@ void usage(char const* appName)
370
370
fprintf (stderr, " usage: %s <input>\n " , appName);
371
371
}
372
372
373
+ char * readAllText (char const * fileName)
374
+ {
375
+ FILE * f;
376
+ fopen_s (&f, fileName, " rb" );
377
+ if (!f)
378
+ {
379
+ return " " ;
380
+ }
381
+ else
382
+ {
383
+ fseek (f, 0 , SEEK_END);
384
+ auto size = ftell (f);
385
+ char * buffer = new char [size + 1 ];
386
+ memset (buffer, 0 , size + 1 );
387
+ fseek (f, 0 , SEEK_SET);
388
+ fread (buffer, sizeof (char ), size, f);
389
+ fclose (f);
390
+ return buffer;
391
+ }
392
+ }
393
+
394
+ void writeAllText (char const *srcFileName, char const * fileName, char * content)
395
+ {
396
+ FILE * f = nullptr ;
397
+ fopen_s (&f, fileName, " wb" );
398
+ if (!f)
399
+ {
400
+ printf (" %s(0): error G0001: cannot write file %s\n " , srcFileName, fileName);
401
+ }
402
+ else
403
+ {
404
+ fwrite (content, 1 , strlen (content), f);
405
+ fclose (f);
406
+ }
407
+ }
408
+
373
409
int main (
374
410
int argc,
375
411
char ** argv)
@@ -416,8 +452,9 @@ int main(
416
452
417
453
Node* node = readInput (input, inputEnd);
418
454
455
+ // write output to a temporary file first
419
456
char outputPath[1024 ];
420
- sprintf_s (outputPath, " %s.h" , inputPath);
457
+ sprintf_s (outputPath, " %s.temp. h" , inputPath);
421
458
422
459
FILE* outputStream;
423
460
fopen_s (&outputStream, outputPath, " w" );
@@ -426,5 +463,17 @@ int main(
426
463
427
464
fclose (outputStream);
428
465
466
+ // update final output only when content has changed
467
+ char outputPathFinal[1024 ];
468
+ sprintf_s (outputPathFinal, " %s.h" , inputPath);
469
+
470
+ char * allTextOld = readAllText (outputPathFinal);
471
+ char * allTextNew = readAllText (outputPath);
472
+ if (strcmp (allTextNew, allTextOld) != 0 )
473
+ {
474
+ writeAllText (inputPath, outputPathFinal, allTextNew);
475
+ }
476
+ remove (outputPath);
477
+
429
478
return 0 ;
430
479
}
0 commit comments