Concatenate chars

24 Jul 2011

Hello.

My current project requires some variable filenames. Those filenames include a number, which is stored as an integer. Therefore my current aim is to concatenate a char with an integer. For instance some pseudo-code:

int a = 1234;
char path[100];
path = "/sd/example/" + (char)a + ".txt";
FILE *fp = fopen(path,"r");

Do you have any idea to solve this issue?

Thanks!

24 Jul 2011

you can do with a string class or the old sprintf method.

sprintf(path, "/sd/example/%d.txt", a);

or safer

#define MAX_BUF_LEN  100

snprintf(path, MAX_BUF_LEN, "/sd/example/%d.txt", a);
24 Jul 2011

The sprintf method has been perfectly successful. Nonetheless the reading routine does not work at all:

int a = 1234;
char content[100];
char path[100];
opendir("/sd/example");
sprintf(path, "/sd/example/%d.txt", a);
FILE *fp = fopen(path,"r");
int ii = 0;
while (!feof(fp)) {
    content[ii] = fgetc(fp);
    ii = ii + 1;
}
fclose(fp);
24 Jul 2011

Might be time to resort to some printf() style debugging.

Do you already have a terminal connected to the mbed via the virtual USB serial port? If you need help getting a terminal connected to the mbed, you should check out this link and on Windows you will want to look at this link to learn more about the driver that will need to be installed.

If you use this version of the code, what do you see displayed in the terminal?

    int a = 1234;
    char content[100];
    char path[100];
    
    sprintf(path, "/sd/example/%d.txt", a);
    FILE *fp = fopen(path,"r");
    if (NULL == fp)
    {
        error("Failed to open %s.\n", path);
    }

    int ii = 0;
    while (!feof(fp) && ii < 100)
    {
        content[ii] = fgetc(fp);
        ii = ii + 1;
    }
    if (100 == ii)
    {
        error("File %s is too large to fit in content buffer.\n", path);
    }
    else
    {
        printf("Successfully read in %d bytes from %s.\n", ii, path);
    }
    
    fclose(fp);
24 Jul 2011

The above code seems to be unable to handle 10-digit integers, for instance: /sd/example/1234567891.txt. With only 8-digit integers everything is working fine.

25 Jul 2011

The 'int' type is 32-bit so its range is -2,147,483,648 to 2,147,483,647

You would need to use 64-bit integers to increase the range. For example:

    unsigned long long a = 123456789012345ULL;
....    
    sprintf(path, "/sd/example/%llu.txt", a);

The only other thing you will have to deal with is whether the sd file system that you are using can handle anything other than the old 8.3 filename format. I haven't used it so I don't know. I do know that the LocalFileSystem has a 8.3 limitation where the name can only be 8 characters long and the extension 3 characters long.