xref: /XiangShan/tools/readmemh/split-readmemh.c (revision 5a7b942b030b799f8086bf9a6096981200fb8b46)
1 #include <stdio.h>
2 #include <assert.h>
3 #include <stdint.h>
4 #include <string.h>
5 
6 char outname [4][4096];
7 
8 int main(int argc, char *argv[]) {
9   assert(argc == 2);
10 
11   FILE *in = fopen(argv[1], "rb");
12   assert(in != NULL);
13 
14   strcat(stpcpy(outname[0], argv[1]), "_0");
15   strcat(stpcpy(outname[1], argv[1]), "_1");
16   strcat(stpcpy(outname[2], argv[1]), "_2");
17   strcat(stpcpy(outname[3], argv[1]), "_3");
18 
19   FILE *out[4];
20   out[0] = fopen(outname[0], "w");
21   out[1] = fopen(outname[1], "w");
22   out[2] = fopen(outname[2], "w");
23   out[3] = fopen(outname[3], "w");
24   assert(out[0] != NULL && out[1] != NULL && out[2] != NULL && out[3] != NULL);
25 
26   char line[128];
27   int idx = 0;
28   while (fgets(line, 128, in) != NULL) {
29     if (line[0] == '@') {
30       uint32_t addr;
31       sscanf(line + 1, "%x", &addr);
32       assert(addr % 4 == 0);
33       fprintf(out[0], "\n@%08x\n", addr / 4);
34       fprintf(out[1], "\n@%08x\n", addr / 4);
35       fprintf(out[2], "\n@%08x\n", addr / 4);
36       fprintf(out[3], "\n@%08x\n", addr / 4);
37       idx = 0;
38     }
39     else {
40       // remove white spaces at the end
41       char *p = line + strlen(line) - 1;
42       while (p >= line && (*p == ' ' || *p == '\n' || *p == '\r')) p --;
43       p[1] = '\0';
44 
45       p = line;
46       char *byte;
47       while ((byte = strsep(&p, " "))) {
48         fprintf(out[idx % 4], "%s ", byte);
49         idx ++;
50       }
51 
52       if ((idx >> 2) % 16 == 0) {
53         fprintf(out[0], "\n");
54         fprintf(out[1], "\n");
55         fprintf(out[2], "\n");
56         fprintf(out[3], "\n");
57       }
58     }
59   }
60 
61   fclose(in);
62   fclose(out[0]);
63   fclose(out[1]);
64   fclose(out[2]);
65   fclose(out[3]);
66 
67   return 0;
68 }
69