4

  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")

Saifur Rahman Mohsin
  • 929
  • 1
  • 11
  • 37
  • The `.` operator doesn't concatenate strings in C or C++, it's for member access for things like struct instances. What you're trying to do is concatenate/append strings, see here: http://stackoverflow.com/questions/308695/c-string-concatenation – wkl Oct 27 '11 at 18:50

5 Answers5

7
#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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
4

Have a look at strcat:

An example:

#include <string.h>
char alpha[14] = "something";
strcat(alpha, " bla"); // "something bla"
printf("%s\n", alpha);
Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
  • The use of beta is superfluous. strcat will essentially put the "bla" in the area left by alpha. Then it will set beta=alpha. you would have as follows: Before: *alpha is "something" after: *alpha is "somethingbla" and beta=alpha – James Matta Oct 27 '11 at 19:01
1

Using the dot won't work.

The function you are looking for is called strcat.

Dennis
  • 14,264
  • 2
  • 48
  • 57
1

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");
James Matta
  • 1,562
  • 16
  • 37
-3

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.

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Turcogj
  • 151
  • 1
  • 8