Hocus68
Hocus68

Reputation: 13

Rename a char variable in C within a for loop

I'm a beginner in C and I spent a lot of time on my problem and I can't figure out the solution.

I want to update the name of a file filename_2 (char) using filename_1 as a prefix within a for loop in C.

I do not want to modify the name of filename_1, because it is used by other functions.

Here is my code and what I'm looking for just after.

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

int main()
{
    int j;
    char filename_1[40]="test";
    char nummbr[40];
    char *filename_2 = NULL;
    filename_2 = filename_1;
    
    
    for( j = 0; j<12; j++)
    {

        sprintf(nummbr, "%d", j); // transform int into char --> for concatenation
        
        if (j < 21){            
            strcat(filename_2, "_00");
            strcat(filename_2, nummbr);
        }else{
            strcat(filename_2, "_0");
            strcat(filename_2, nummbr);
        }  

        /* do things with the file */
        printf("member: %i %s\n",j, filename_2);
       
    }
    return 0;
}

I have the following result:

member: 0 test_pr_fc_000
member: 1 test_pr_fc_000_001
...
member: 10 test_pr_fc_000_001_002_003 ..._010
..

I want :

member: 0 test_000
member: 1 test_001
...
member: 20 test_020

Upvotes: 0

Views: 286

Answers (1)

dbush
dbush

Reputation: 224577

You keep appending to filename_2 (which points to filename_1) on each iteration of the loop without resetting, so each iteration just appends to the text of the previous.

First, make filename_2 an array instead of a pointer. Then start each iteration by using strcpy to copy filename_1 to the start of filename_2.

char filename_2[40];

for( j = 0; j<12; j++)
{
    strcpy(filename_2, filename_1);
    ...

Also, this:

if (j < 21){

Should probably be:

if (j < 10){

Upvotes: 1

Related Questions