Confused about command prompt, Visual Studio exe&#

2019-08-01 08:29发布

The title doesn't really do this topic justice. It's actually quite simple, my problem that is. I have a program (code below) written in the C language. I want this program to create an exe file that can be ran through the command prompt console window and that will also take a text file as a parameter. So, long story short; I need it to say this on the command line in CMD:

C:\Users\Username\Desktop\wrapfile.exe content.txt

My only problem is getting the code right. I want to tell Visual Studio: "The file you should open is given in the command prompt window as a parameter, there is no set location..."

How do I do that?

Here is my working code (Although you will have to change a few things in the *fp definition.

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char *argv[])
{

    FILE *fp; // declaring variable 


    fp = fopen("c:\\users\\*Put you're PC username here*\\Desktop\\contents.txt", "rb"); // opens the file


    if (fp != NULL) // checks the return value from fopen
    {
        int i;
        do
        {
            i = fgetc(fp);     // scans the file 
            printf("%c",i);
            printf(" ");
        }
        while(i!=-1);
        fclose(fp);
    }
    else
    {
        printf("Error.\n");
    }
}

Thanks everyone!

1条回答
放我归山
2楼-- · 2019-08-01 09:25

As Ken said above, the arguments of the main method are the values that you pass in from the command line. Argc is 'argument count' and argv is 'argument values'. So to open the fist argument passed in from the command line, change

fp = fopen("c:\\users\\*Put you're PC username here*\\Desktop\\contents.txt", "rb"); // opens the file

to

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

Just make sure to do error checking (ie argv[1] is not null) before you try to fopen the input. Also FYI, in your case argv[0] will be the name of your executable.

查看更多
登录 后发表回答