Confused about command prompt, Visual Studio exe's and text files?

时光毁灭记忆、已成空白 提交于 2020-01-05 05:49:11

问题


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:


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.



来源:https://stackoverflow.com/questions/13734843/confused-about-command-prompt-visual-studio-exes-and-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!