Question

How to create multiple a text file in strcat

In my case, for example i input three name

./test paul tony john , so i use strcat to add ".dat"

but i cannot set three name is paul.dat tony.dat john.dat

the result is paul.dat.dat.dat dat.dat.dat .dat.dat

int main(int argc, char *argv[]){

int pid, myid ,cid; 
int num_name;
int i, n, returnpid;
int val;

num_name = argc-1;

for (i =1; i<=num_name; i++) {
       strcat(argv[i],".dat");


    }
Was it helpful?

Solution 2

You cannot append ".dat" directly to argv[i] because argv[i] has a allocated size that can only hold its original content.

To understand what is happening, imagine argv is something like this:

char buffer[] = "./test\0paul\0tony\0john\0";
char *argv[4] = { &buffer[0], &buffer[7], &buffer[12], &buffer[17] };

So as you can see, if you write something after "paul" you will overwrite "tony" and break the whole thing because they are serialized in the same buffer.

To workaround this, you have to copy each argv[i] to a bigger buffer where you can safely make the modifications. For instance:

int i;
char filename[1024];
for (i = 1; i < argc; ++i) {
    sprintf(filename, "%s.dat", argv[i]);
    // ... do stuff
}

Then you will have a variable filename containing the desired filename without corrupting argv.

OTHER TIPS

When you call strcat(), you need to make sure there is enough space in the buffer allocated for the first argument for the string you are trying to add.

You can't add things directly to the elements of argv[] with strcat().

Allocate a new buffer that is large enough for both strings (including a nul character at the end), strcpy() the argv[] element into that buffer, and then perform the strcat().

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
    int pid, myid ,cid; 
    int num_name;
    int i, n, returnpid;
    int val;

    num_name = argc-1;

    for (i =1; i<=num_name; i++) {
        char *p;
        p=(char*)malloc(sizeof(char)*(strlen(argv[i])+5));//5= 4(.dat) + 1(EOS)
        sprintf(p, "%s.dat", argv[i]);
        argv[i]=p;
    }
    for(i =1; i<=num_name; i++)
        printf("%s\n", argv[i]);
   return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top