《操作系统》的实验代码。

43 rivejä
1.2 KiB

12 vuotta sitten
  1. #include <stdio.h>
  2. #include <errno.h>
  3. #include <string.h>
  4. #include <sys/stat.h>
  5. int
  6. main(int argc, char *argv[]) {
  7. struct stat st;
  8. if (argc != 3) {
  9. fprintf(stderr, "Usage: <input filename> <output filename>\n");
  10. return -1;
  11. }
  12. if (stat(argv[1], &st) != 0) {
  13. fprintf(stderr, "Error opening file '%s': %s\n", argv[1], strerror(errno));
  14. return -1;
  15. }
  16. printf("'%s' size: %lld bytes\n", argv[1], (long long)st.st_size);
  17. if (st.st_size > 510) {
  18. fprintf(stderr, "%lld >> 510!!\n", (long long)st.st_size);
  19. return -1;
  20. }
  21. char buf[512];
  22. memset(buf, 0, sizeof(buf));
  23. FILE *ifp = fopen(argv[1], "rb");
  24. int size = fread(buf, 1, st.st_size, ifp);
  25. if (size != st.st_size) {
  26. fprintf(stderr, "read '%s' error, size is %d.\n", argv[1], size);
  27. return -1;
  28. }
  29. fclose(ifp);
  30. buf[510] = 0x55;
  31. buf[511] = 0xAA;
  32. FILE *ofp = fopen(argv[2], "wb+");
  33. size = fwrite(buf, 1, 512, ofp);
  34. if (size != 512) {
  35. fprintf(stderr, "write '%s' error, size is %d.\n", argv[2], size);
  36. return -1;
  37. }
  38. fclose(ofp);
  39. printf("build 512 bytes boot sector: '%s' success!\n", argv[2]);
  40. return 0;
  41. }