Concatenate string with integer array and write to file?

Asked

Viewed 330 times

1

I have a dynamic vector of integers. For example:

1 2 4 6 8 9 10

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

[B]: 

And record this in a row of the file, 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 doing some research, but I couldn’t even get a clue how to do it, so I don’t have any code that’s in the way of doing that.

Can someone at least give me a way to do that? If you have a command, a demonstration, or whatever.

  • 3

    fprintf(arquivo, "[B]:"); for (int k = 0; k < n; k++) fprintf(arquivo, " %d", vetor[k]); fprintf(arquivo, "\n");

  • Let’s eliminate the dynamic vector for now. Can you already create a file and write anything static inside it? I ask this because you can split your problem into parts. First understand how to open, write and close a file. After that, you leave for the 2nd step, which is to write the dynamic vector. I can say that if you do the 1st part, the 2nd part will be trivial.

  • What @pmg worked perfectly. Yes I know the basics of the file, I wasn’t reminded of the fprintf and thought there might be another way.

  • @pmg Is there no way to put as an answer? So we can vote and the answer can be accepted. With this we can document the question more clearly. Thank you!!! Ah, put an explanation in the code in comment form, if you accept my proposal.

1 answer

2


You don’t need to build the string dynamically in memory: you can use fprintf() and print directly to the archive

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 build 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 '\0'
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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.