bom.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "bom.h"
  2. #define BOMSIZE 3
  3. #define CHUNKSIZE 1024
  4. unsigned char bom[] = { 0xEF, 0xBB, 0xBF };
  5. int checkBOM(const char *filePath) {
  6. FILE *inputFile = fopen(filePath, "r");
  7. if (inputFile == NULL) return ERROROPENINPUT;
  8. unsigned char check[BOMSIZE];
  9. if (BOMSIZE != fread(check, BOMSIZE, 1, inputFile)) {
  10. if (feof(inputFile)) return NOBOM;
  11. if (ferror(inputFile)) return ERRORINPUT;
  12. }
  13. if (fclose(inputFile)) return ERRORCLOSEINPUT;
  14. if (!memcmp(&bom, check, BOMSIZE)) return HASBOM;
  15. return NOBOM;
  16. }
  17. const char *tempFileName = "tempFile";
  18. int removeBOM(const char *filePath) {
  19. if (NOBOM == checkBOM(filePath)) return SUCCESS;
  20. FILE *inputFile = fopen(filePath, "r");
  21. if (inputFile == NULL) return ERROROPENINPUT;
  22. if (fseek(inputFile, BOMSIZE, SEEK_SET)) return ERRORSEEK;
  23. FILE *tempFile = fopen(tempFileName, "w");
  24. if (tempFile == NULL) return ERROROPENTEMP;
  25. char buffer[CHUNKSIZE];
  26. do {
  27. size_t read = fread(buffer, 1, CHUNKSIZE, inputFile);
  28. size_t written = fwrite(buffer, 1, read, tempFile);
  29. if (written != read) {
  30. fclose(tempFile);
  31. fclose(inputFile);
  32. remove(tempFileName);
  33. return ERRORWRITINGTEMP;
  34. }
  35. } while (!feof(inputFile));
  36. if (fclose(tempFile)) return ERRORCLOSETEMP;
  37. if (fclose(inputFile)) return ERRORCLOSEINPUT;
  38. if (remove(filePath)) return ERRORREMOVE;
  39. if (rename(tempFileName, filePath)) return ERRORRENAME;
  40. return SUCCESS;
  41. }
  42. int addBOM(const char *filePath) {
  43. if (HASBOM == checkBOM(filePath)) return SUCCESS;
  44. FILE *inputFile = fopen(filePath, "r");
  45. if (inputFile == NULL) return ERROROPENINPUT;
  46. FILE *tempFile = fopen(tempFileName, "w");
  47. if (tempFile== NULL) return ERROROPENTEMP;
  48. size_t written = fwrite(bom, 1, BOMSIZE, tempFile);
  49. if (written != BOMSIZE) return ERROROUTPUT;
  50. char buffer[CHUNKSIZE];
  51. while(1) {
  52. size_t read = fread(buffer, 1, CHUNKSIZE, inputFile);
  53. written = fwrite(buffer, 1, read, tempFile);
  54. if (written != read) {
  55. fclose(tempFile);
  56. fclose(inputFile);
  57. remove(tempFileName);
  58. return ERRORWRITINGTEMP;
  59. }
  60. if (feof(inputFile)) break;
  61. }
  62. if (fclose(tempFile)) return ERRORCLOSETEMP;
  63. if (fclose(inputFile)) return ERRORCLOSEINPUT;
  64. if (remove(filePath)) return ERRORREMOVE;
  65. if (rename(tempFileName, filePath)) return ERRORRENAME;
  66. return SUCCESS;
  67. }