如何在C中创建命令行程序

时间:2017-06-16 16:05:33

标签: c

我想在C中创建一个命令行程序,该程序允许用户输入我的自定义命令,选择一个选项,并对用户文件执行功能。程序将根据选择的选项执行不同的功能。该程序还应能够识别计算机上是否存在文件。

例如,如果我的自定义命令为encodethis,则用户将输入encodethis -e <filename>对文件进行编码。

这是我到目前为止所做的尝试,以检查用户是否输入了正确的参数。

#include <stdio.h>
#include <string.h>

/* main function to copy strings*/

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

    if (argc == 3) {
        if (strcmp (argv[0], "myencode") == 0) {
            if (strcmp (argv[1], "-e") ==0) {
                 /* Check user input against files in computer*/

现在我的问题是以某种方式检查用户输入的文件名与他的计算机中的文件是否存在。我不知道如何检查argv[]数组中的第3个值,因为它是由用户输入的,并且最初是未定义的。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

#include <stdio.h>
#include <string.h>

/* main function to copy strings*/

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

    if (argc == 3) {
        if (strcmp (argv[0], "myencode") == 0) {
            if (strcmp (argv[1], "-e") ==0) {
                 /* Check user input against files in computer*/
                FILE *fp;
                fp = fopen(argv[2],"r+");
                if (fp!=NULL){
                    /* your stuff goes here, don't forget to close
                       the file with fclose(fp) 
                    */
                }else{
                printf("Error: could not open file\n");
            }
        }
    }
return 0;
}

来源:C File I/O

相关问题