b2c.c 1000 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <sys/stat.h>
  4. #include <sys/types.h>
  5. #include <unistd.h>
  6. void print_usage(void )
  7. {
  8. printf("Usage: b2c bin_img tar_file.h symname\n");
  9. exit(1);
  10. }
  11. void open_file(char *fn, int *fd, int *sz)
  12. {
  13. struct stat buf;
  14. *fd = open(fn, O_RDONLY);
  15. if (fd < 0) {
  16. printf("cannot open %s\n", fn);
  17. exit(1);
  18. }
  19. fstat(*fd, &buf);
  20. if (buf.st_size <= 10*1024) {
  21. printf("Is this a right file %s, size = %ld\n", fn, buf.st_size);
  22. exit(1);
  23. }
  24. *sz = (int)buf.st_size;
  25. }
  26. int main(int argc, char **argv)
  27. {
  28. int sfd, ssz, red, i;
  29. int buf[1024];
  30. char *sfn, *tfn, *symname;
  31. FILE *tfd;
  32. if (argc != 4) {
  33. print_usage();
  34. }
  35. sfn = argv[1];
  36. tfn = argv[2];
  37. symname = argv[3];
  38. open_file(sfn, &sfd, &ssz);
  39. tfd = fopen(tfn, "w");
  40. fprintf(tfd, "int %s[] = {\n", symname);
  41. while((red=read(sfd, buf, 1024*sizeof(int)))) {
  42. for (i=0; i<red/sizeof(int); i++)
  43. fprintf(tfd, "0x%x, \n", buf[i]);
  44. }
  45. fprintf(tfd, "};");
  46. fclose(tfd);
  47. return 0;
  48. }