JTN
JTN

Reputation: 13

Converting commandline argument to string in C

I am new to programming. I want to take one commandline argument which is a filename and open that particular file and copy the contents to another file. I don't know how to convert the commandline argument to a string or file pointer. I checked strcpy and std::string which I found online but it didn't work. Please help me. I have pasted my code below

    #include<string.h>
    #include <stdio.h>
    #include <stdlib.h>
    void main(int argc, char *argv[])
    {
    char *inp;
    strcpy(inp,argv[1]);
    FILE *fp;
    char str[5];
    //printf("Enter the file name:");
    //scanf("%s",fname);

     if ((fp= fopen(inp, "r")) == NULL) {
     printf("cannot open file");
     exit(1);
     }
     FILE *fp1;
     fp1=fopen("out.txt","w+");
     while(!feof(fp)) {
     fgets(str,4,fp);
     printf("%s",str);
     fprintf(fp1,"%s",str);
      }

     fclose(fp);
      fclose(fp1);
      }

Upvotes: 0

Views: 123

Answers (1)

PC Luddite
PC Luddite

Reputation: 6088

Why not char *inp = argv[1];?

Or better yet:

fp = fopen(argv[1], "r");

The problem with your code is this:

char *inp;
strcpy(inp,argv[1]);

You're copying argv[1] into inp, but you have no idea what inp points to. If you really want to go that route, you have to allocate memory for inp.

char *inp = malloc(strlen(argv[1]) + 1); /* allocate enough for the string and null-terminator */
strcpy(inp,argv[1]); /* copy the contents */

Just remember to free() afterwards.

P.S. Never use while(!feof(fp)). Just use while(fgets(str,4,fp)). See this question for more info.

Upvotes: 2

Related Questions