-2

Hello i just started to programm in C and i am trying to read a file and give the file name as argument without the ending .txt . I want to add .txt in my code : ./myexample.exe file

if i use file.txt there is no problem but i dont know how to change argv[1] i tried char *n = argv[1] + ".txt"; it doesnt works and i dont know anything else..

int main(int argc, char* argv[]) {
      char *n = argv[1] +".txt";
      FILE *fp1;
      fp1 = fopen(n , "r");

Thats what i get if i use char *n = argv[1]+".txt"

error: invalid operands to binary + (have 'char *' and 'char *')

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
C.Z
  • 41
  • 1
  • 6

3 Answers3

3

In your code,

 char *n = argv[1] +".txt";

does not do what you think it does. In C, the + cannot be used to concatenate strings.

FYI, from C11, chapter §6.5.6

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

Both the operands cannot be of pointer-to-object type.

If you meant to concatenate strings, use strcat() but make sure

  • the destination is modifiable (attempt to modify string literal is UB)
  • the destination got enough space to contain the final result (shorter destination lead to access out of bound memory invoking UB, again).
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

You can't concatenate strings with +. Use strcpy and strcat:

char n[256];
strcpy(n, argv[1]);
strcat(n, ".txt");

Make sure that n is large enough to hold the filename + extension.

yassin
  • 642
  • 2
  • 7
  • 18
1

This is kind of annoying to do safely: you need to be careful to make a big enough char array to hold the whole string. One way:

size_t arglen=strlen(argv[1]);
char* filename=malloc(arglen+5); //Enough to hold the whole string
strcpy(filename,argv[1]);
strcat(filename,".txt");

Be sure to free the pointer later.

Chris
  • 1,613
  • 17
  • 24