bom.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. for (int i = 0; i < BOMSIZE; i++)
  43. if (EOF == fputc(bom[i], tempFile)) return ERROR;
  44. int c = fgetc(inputFile);
  45. while (c != EOF) {
  46. if (EOF == fputc(c, tempFile)) return ERROR;
  47. c = fgetc(inputFile);
  48. }
  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. }