rCan rCan - 1 year ago 79
C Question

add string to given command line argument in C

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 *')

Answer Source

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download