bom.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 ERROR;
  8. unsigned char check[BOMSIZE];
  9. if (BOMSIZE != fread(check, BOMSIZE, 1, inputFile)) {
  10. if (feof(inputFile)) return NOBOM;
  11. if (ferror(inputFile)) return ERROR;
  12. }
  13. if (fclose(inputFile)) return ERROR;
  14. if (!memcmp(&bom, check, BOMSIZE)) return HASBOM;
  15. return NOBOM;
  16. }
  17. 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 ERROR;
  22. if (fseek(inputFile, BOMSIZE, SEEK_SET)) return ERROR;
  23. FILE *tempFile = fopen(tempFileName, "w");
  24. if (tempFile == NULL) return ERROR;
  25. char buffer[CHUNKSIZE];
  26. do {
  27. int read = fread(buffer, 1, CHUNKSIZE, inputFile);
  28. fwrite(buffer, 1, read, tempFile);
  29. } while (!feof(inputFile));
  30. if (fclose(tempFile)) return ERROR;
  31. if (fclose(inputFile)) return ERROR;
  32. if (remove(filePath)) return ERROR;
  33. if (rename(tempFileName, filePath)) return ERROR;
  34. return SUCCESS;
  35. }
  36. int addBOM(const char *filePath) {
  37. if (HASBOM == checkBOM(filePath)) return SUCCESS;
  38. FILE *inputFile = fopen(filePath, "r");
  39. if (inputFile == NULL) return ERROR;
  40. FILE *tempFile = fopen(tempFileName, "w");
  41. if (tempFile== NULL) return ERROR;
  42. int written = fwrite(bom, 1, BOMSIZE, tempFile);
  43. if (written != BOMSIZE) return ERROR;
  44. char buffer[CHUNKSIZE];
  45. do {
  46. int read = fread(buffer, 1, CHUNKSIZE, inputFile);
  47. fwrite(buffer, 1, read, tempFile);
  48. } while (!feof(inputFile));
  49. if (fclose(tempFile)) return ERROR;
  50. if (fclose(inputFile)) return ERROR;
  51. if (remove(filePath)) return ERROR;
  52. if (rename(tempFileName, filePath)) return ERROR;
  53. return SUCCESS;
  54. }