为什么我的程序不能正确检查参数的数量?

Why does my program not check the number of arguments correctly?

好吧,我正在为必须从输入文件读取字符串的二叉搜索树编写代码:"input.txt" 并且我正在尝试提供我的程序命令行参数。我的程序应该采用两个命令行参数,程序名称然后是文件名称。如果 args 的数量不是两个,我会对其进行错误检查以停止程序。当我 运行 "./a.out main.c input.txt"?

时,为什么我的程序仍然跳闸错误检查

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 15

typedef struct treeNode{
  char string[MAXLEN+1];
  struct treeNode *left;
  struct treeNode *right;
}treeNode;

treeNode * insert(treeNode *node, char s[MAXLEN]){
  if(node == NULL){
    treeNode *temp;
    temp = (treeNode *)malloc(sizeof(treeNode));
    strncpy(temp -> string, s, sizeof(treeNode));
    temp -> left = NULL;
    temp -> right = NULL;
    return temp;
  }

  else if(strcmp(node->string, s)>0){
    node -> right = insert(node->right, s);
  }
  else if(strcmp(node->string, s)<0){
    node -> left = insert(node->left, s);
  }
  else if(strcmp(node->string, s) == 0){
    node -> left = insert(node->left, s);
  }

}

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

  treeNode *root = NULL;

  FILE *ifp;
  FILE *ofp;
  char s[MAXLEN+1];

  if(argc != 3){
    fprintf(stderr, "Usage: %s file\n", argv[1]); exit(1);
  }

  if((ifp = fopen(argv[2], "r")) == NULL){
    fprintf(stderr, "Could not open file: %s\n", argv[2]); exit(1);
  }

  ofp = fopen("output.txt", "w+");

  fgets(s, MAXLEN, ifp);

  insert(root, s);

  fprintf(ofp, "%s\n", root->string);

  return 0;
}

argc 将始终至少为 1,因为 argv[0] 包含可执行文件的路径。 因此,您应该检查 if ( argc != 3 ),因为您从命令行传递了 2 个参数。

当你执行 ./a.out main.c input.txt 时,argv[1] 将是 main.cargv[2] 将是 input.txt

在访问 argv 数组中的所需元素时,您在许多地方都偏离了 1,因此请进行适当的更改。在您使用 argv[1] 的地方,您需要将其更改为 argv[2]