bom.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "bom.h"
  2. #define BOMSIZE 3
  3. unsigned char bom[] = { 0xEF, 0xBB, 0xBF };
  4. int checkBOM(char *filePath) {
  5. FILE *inputFile = fopen(filePath, "r");
  6. if (inputFile == NULL) return ERROR;
  7. unsigned char check[BOMSIZE];
  8. if (BOMSIZE != fread(check, BOMSIZE, 1, inputFile)) {
  9. if (feof(inputFile)) return NOBOM;
  10. if (ferror(inputFile)) return ERROR;
  11. }
  12. if (fclose(inputFile)) return ERROR;
  13. if (!memcmp(&bom, check, BOMSIZE)) return HASBOM;
  14. return NOBOM;
  15. }
  16. char *tempFileName = "tempFile";
  17. int removeBOM(char *filePath) {
  18. if (NOBOM == checkBOM(filePath)) return SUCCESS;
  19. FILE *inputFile = fopen(filePath, "r");
  20. if (inputFile == NULL) return ERROR;
  21. if (fseek(inputFile, BOMSIZE, SEEK_SET)) return ERROR;
  22. FILE *tempFile = fopen(tempFileName, "w");
  23. if (tempFile== NULL) return ERROR;
  24. int c = fgetc(inputFile);
  25. while (c != EOF) {
  26. if (EOF == fputc(c, tempFile)) return ERROR;
  27. c = fgetc(inputFile);
  28. }
  29. if (fclose(tempFile)) return ERROR;
  30. if (fclose(inputFile)) return ERROR;
  31. if (remove(filePath)) return ERROR;
  32. if (rename(tempFileName, filePath)) return ERROR;
  33. return SUCCESS;
  34. }
  35. int addBOM(char *filePath) {
  36. if (HASBOM == checkBOM(filePath)) return SUCCESS;
  37. FILE *inputFile = fopen(filePath, "r");
  38. if (inputFile == NULL) return ERROR;
  39. FILE *tempFile = fopen(tempFileName, "w");
  40. if (tempFile== NULL) return ERROR;
  41. for (int i = 0; i < BOMSIZE; i++)
  42. if (EOF == fputc(bom[i], tempFile)) return ERROR;
  43. int c = fgetc(inputFile);
  44. while (c != EOF) {
  45. if (EOF == fputc(c, tempFile)) return ERROR;
  46. c = fgetc(inputFile);
  47. }
  48. if (fclose(tempFile)) return ERROR;
  49. if (fclose(inputFile)) return ERROR;
  50. if (remove(filePath)) return ERROR;
  51. if (rename(tempFileName, filePath)) return ERROR;
  52. return SUCCESS;
  53. }