0

I'm writing a C program which I was reading a bunch of data from a txt.file into a list of struct. And I was just told that we can't read data from another file and all the data should be contained in one c file. Is there any way to create the list without hard coding one by one?

Parts of my data is like following:

.
period
?
Question Mark
!
Point
-
Dash
/
slash
+=
Plus equal
>=
greater than or equal

And I want to put them in the following list, except for doing it line by line, is there any better way to build this long list?

typedef struct info
{
   char ch[10];
   char name[50];
}INFO;

int main(int argc, char* argv[])
{
    INFO list[50];
    strcpy(list[0].ch,".");
    strcpy(list[0].name,"period");
   ..... 
}


Boba
  • 87
  • 10

1 Answers1

1

It shouldn't be too hard to convert the text file into C code with a few search and replace operations as long as you have an editor that can handle regular expressions.

Or you could even write a C program to do this conversion for you. Something like this perhaps:

int main() {
    FILE *f = fopen("file.txt", "r");
    char ch[10], name[50];
    int i = 0;
    
    puts("INFO list[] = {");
    while (1) {
        if (fscanf(f, "%[^\n] ", ch) != 1 || fscanf(f, "%[^\n] ", name) != 1) {
            break;
        }
        printf("    { \"%s\", \"%s\" },\n", ch, name);
        i++;
    }
    printf("};\n\n#define LIST_LENGTH  %d\n", i);
    return 0;
}

Assuming the data you provided above is contained in a file called file.txt, this should output the following:

INFO list[] = {
    { ".", "period" },
    { "?", "Question Mark" },
    { "!", "Point" },
    { "-", "Dash" },
    { "/", "slash" },
    { "+=", "Plus equal" },
    { ">=", "greater than or equal" },
};

#define LIST_LENGTH  7
r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • Ive tried this way but it shows `initializer-string for char array is too long`, it there a limit to initialize an array? – Boba Sep 29 '20 at 22:11
  • @AKu Perhaps there's a line in your data that exceeds either the symbol (10) or the symbol description (50) character limit. – Janez Kuhar Sep 29 '20 at 22:23
  • @AKu I suggest you make life easier for yourself by changing the struct contents to `char *ch; char *name;` instead of specifying array lengths. The strings will be stored as `const char*`, but I assume you're not planning to modify them. – r3mainer Sep 29 '20 at 23:01
  • @r3mainer But that does make the memory allocations less contiguous, doesn't it? – Janez Kuhar Sep 29 '20 at 23:07
  • 1
    @JanezKuhar Does it matter? – r3mainer Sep 29 '20 at 23:09