0

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);
      }
3
  • 1
    Just use fopen(argv[1], "r"). The strcpy won't work unless inp points to valid memory, e.g. char inp[100] or char *inp = malloc(100). Also, don't use while(!feof(fp)). Instead use while(fgets(str,4,fp)!=NULL). Commented Oct 6, 2015 at 1:05
  • std::string is C++, so that won't work. Commented Oct 6, 2015 at 1:22
  • Thank you very much for pointing out the wrong way I checked for the EOF Commented Oct 6, 2015 at 1:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.