Saifur Rahman Mohsin
Saifur Rahman Mohsin

Reputation: 1011

How to add a character at end of string

  I have a file copy program that takes from one file and pastes in another file pointer. But, instead of getting targetname from user input i'd like to just add a '1' at the end of the input filename and save. So, I tried something like this...

       .... header & inits ....
       fp=fopen(argv[1],"r");
       fq=fopen(argv[1].'1',"w");
       .... file copy code ....

Yeah it seems stupid but I'm a beginner and need some help, do respond soon. Thanks :D

P.S. Want it in pure C. I believe the dot operator can work in C++.. or atleast i think.. hmm

One more thing, i'm already aware of strcat function.. If i use it, then i'll have to define the size in the array... hmm. is there no way to do it like fopen(argv[1]+"extra","w")

Upvotes: 4

Views: 68049

Answers (5)

Turcogj
Turcogj

Reputation: 161

In C to concatenate a string use strcat(str2, str1)

strcat(argv[1],"1") will concatenate the strings. Also, single quotes generate literal characters while double quotes generate literal strings. The difference is the null terminator.

Upvotes: -3

BLUEPIXY
BLUEPIXY

Reputation: 40145

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

char* stradd(const char* a, const char* b){
    size_t len = strlen(a) + strlen(b);
    char *ret = (char*)malloc(len * sizeof(char) + 1);
    *ret = '\0';
    return strcat(strcat(ret, a) ,b);
}

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

    char *str = stradd(argv[1], "extra");

    printf("%s\n", str);

    free(str);

    return 0;
}

Upvotes: 7

Morten Kristensen
Morten Kristensen

Reputation: 7613

Have a look at strcat:

An example:

#include <string.h>
char alpha[14] = "something";
strcat(alpha, " bla"); // "something bla"
printf("%s\n", alpha);

Upvotes: 4

James Matta
James Matta

Reputation: 1570

Unfortunately . would not work in c++.

A somewhat inelegant but effective method might be to do the following.

int tempLen=strlen(argv[1])+2;
char* newName=(char*)malloc(tempLen*sizeof(char));
strcpy(newName,argv[1]);
strcat(newName,"1");

Upvotes: 1

Dennis
Dennis

Reputation: 14477

Using the dot won't work.

The function you are looking for is called strcat.

Upvotes: 1

Related Questions