繁体   English   中英

从命令行参数打开文本文件

[英]Opening a text file from a command line argument

我正在尝试从命令行参数打开文件。

我已经调试了程序:

当我打印文件的值时,它给出的值是<不完整类型>。

当我打印argv的值时,它给出的值(char **)0x7fffffffe4e0。

当我打印argv [1]的值时,它的值为0x0。

该功能无法打开我的文件。 不知道为什么吗?

我试过了:

if (file.is_open())也是同样的问题。

在我的主要职能中,我通过了:

buildBST(&argv[1]);

BSTTreeData buildBST (char *argv[]){
  vector <string> allwords;

  BSTTreeData Data;
  BinarySearchTree<string> Tree;

  ifstream file (argv[1]);

  char token;

  string listofchars = "";
  string input;

  int distinct = 0;
  int line = 1;

  if (file){
      //if the file opens
      while (getline(file, input)) //gets every line in the file
      {
          for (int i = 0; i < input.size(); ++i) //gets all the contents in the line
          {
              token = input[i]; //each character become a 'token'
              if (isalpha(token))
              {
                  //if the character is an alphabetical character
                  listofchars += token; //append character to a string
                  if (Contains(allwords, listofchars) == false)
                  {
                  //if the current word has not already been added to vector of words
                      //increment the distinct word count
                      distinct += 1;
                      Tree.insert(listofchars); //creates the BST
                      allwords.push_back(listofchars); 
                      //add current word to vector of all the words
                  }
                  else
                  line++; //increments the line number
              }
              else
                  line++; //increments the line number
          }
          listofchars = ""; //creates empty character string
      }
    }
    file.close(); //closes file

    Data.BST = Tree;
    Data.linenumber = line;
    Data.distinctwords = distinct;
    Data.words = allwords;
    return Data;
}

回想一下,在大多数操作系统中, argvmain函数具有以下形式的数组:

argv[0]        = /* path to the program ("zeroth argument") */;
argv[1]        = /* first argument */;
argv[2]        = /* second argument */;
...
argv[argc - 1] = /* last argument */;
argv[argc]     = NULL;

这里的问题是您正在查看第二个参数,而不是第一个。 当你调用buildBST(&argv[1])中的main功能,可以通过一个元件移动的指针,从而使 buildBST所述argv现在指向的第一个参数,而不是第0个参数,因此,表达argv[1]buildBST产生第二个参数,而不是第一个。

解决方案是:

  1. &argv[0] (或等效地,只是argvbuildBSTbuildBST ,然后使用argv[1]获得参数,或者

  2. &argv[1] (或等效地, argv + 1buildBSTbuildBST ,然后使用argv[0]获得参数。

第一种方法可能更具可读性,因为您没有改变argv的含义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM