bom.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. while(1) {
  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. if (feof(inputFile)) break;
  36. };
  37. if (fclose(tempFile)) return ERRORCLOSETEMP;
  38. if (fclose(inputFile)) return ERRORCLOSEINPUT;
  39. if (remove(filePath)) return ERRORREMOVE;
  40. if (rename(tempFileName, filePath)) return ERRORRENAME;
  41. return SUCCESS;
  42. }
  43. int addBOM(const char *filePath) {
  44. if (HASBOM == checkBOM(filePath)) return SUCCESS;
  45. FILE *inputFile = fopen(filePath, "r");
  46. if (inputFile == NULL) return ERROROPENINPUT;
  47. FILE *tempFile = fopen(tempFileName, "w");
  48. if (tempFile== NULL) return ERROROPENTEMP;
  49. size_t written = fwrite(bom, 1, BOMSIZE, tempFile);
  50. if (written != BOMSIZE) return ERROROUTPUT;
  51. char buffer[CHUNKSIZE];
  52. while(1) {
  53. size_t read = fread(buffer, 1, CHUNKSIZE, inputFile);
  54. written = fwrite(buffer, 1, read, tempFile);
  55. if (written != read) {
  56. fclose(tempFile);
  57. fclose(inputFile);
  58. remove(tempFileName);
  59. return ERRORWRITINGTEMP;
  60. }
  61. if (feof(inputFile)) break;
  62. }
  63. if (fclose(tempFile)) return ERRORCLOSETEMP;
  64. if (fclose(inputFile)) return ERRORCLOSEINPUT;
  65. if (remove(filePath)) return ERRORREMOVE;
  66. if (rename(tempFileName, filePath)) return ERRORRENAME;
  67. return SUCCESS;
  68. }