Concatenate string with integer vector and write to file?

1

I have a dynamic integer vector. For example:

1 2 4 6 8 9 10

I want to attach it to a string, like this, for example:

[B]: 

And write this to a file line, then read the file with the following output, for example, assuming the program was run three times:

[B]: 1 2 4 6 8 9 10
[B]: 4 5 6 7 8
[B]: 3 6 7

I've been searching, but I have not been able to figure out how to do it, so I do not have any code that's in the way of doing that.

Can anyone give me one way to do this? If you have a command, a demonstration, or whatever.

    
asked by anonymous 05.12.2015 / 21:45

1 answer

2

You do not need to build the string dynamically in memory: you can use fprintf() and print directly to the file

fprintf(arquivo, "[B]:");              // [B]:
for (int k = 0; k < n; k++) {
    fprintf(arquivo, " %d", vetor[k]); // 4 5 6 7 8 ...
}
fprintf(arquivo, "\n");                // newline

If you really want to construct the string dynamically, use snprintf() (C99) to calculate the required space.

char *result;
size_t bytesneeded = 0;
for (int k = 0; k < n; k++) bytesneeded += snprintf(0, 0, " %d", vetor[k]);
result = malloc(bytesneeded + 5 + 1); // espaco para "[B]:\n" e '
fprintf(arquivo, "[B]:");              // [B]:
for (int k = 0; k < n; k++) {
    fprintf(arquivo, " %d", vetor[k]); // 4 5 6 7 8 ...
}
fprintf(arquivo, "\n");                // newline
' if (!result) /* erro */; int count = sprintf(result, "[B]:"); for (int k = 0; k < n; k++) count += sprintf(result + count, " %d", vetor[k]); sprintf(result + count, "\n"); /* usa result, por exemplo fprintf(arquivo, "%s", result); */ free(result);
    
07.12.2015 / 10:23