bom.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. do {
  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. } while (!feof(inputFile));
  61. if (fclose(tempFile)) return ERRORCLOSETEMP;
  62. if (fclose(inputFile)) return ERRORCLOSEINPUT;
  63. if (remove(filePath)) return ERRORREMOVE;
  64. if (rename(tempFileName, filePath)) return ERRORRENAME;
  65. return SUCCESS;
  66. }