【发布时间】:2021-03-20 09:44:55
【问题描述】:
运行此程序时,我似乎收到了 seg fault core dumped 错误。据我所知,段错误是由尝试访问越界引起的,所以我不确定为什么会发生这种情况。 在用 cout 测试了各个点之后,我觉得带有 optind 变量的 if 语句是负责任的,尽管我不知道为什么。我打算让它检查下一个 arg 是否不是一个选项(也就是一个输入)然后执行一些东西。
#include<iostream>
#include<string.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <cstring>
using namespace std;
class dirls
{
public:
dirls();
dirls(bool a, bool d, bool f, bool l, bool h);
void print_usage(string s);
void longlisting(string dir, vector<string>& files);
void getdir(string dir, vector<string>& files, bool recursive);
void initiate(string s, vector<string>& files, vector<string>& paths);
bool ishflag() { return fflag; };
private:
bool aflag;
bool dflag;
bool fflag;
bool lflag;
bool hflag;
};
dirls::dirls()
{
aflag = false;
dflag = false;
fflag = false;
lflag = false;
hflag = false;
}
dirls::dirls(bool a, bool d, bool f, bool l, bool h)
{
aflag = a;
dflag = d;
fflag = f;
lflag = l;
hflag = h;
}
int main(int argc, char* argv[])
{
int opt = 0;
string first = argv[0];
string dir = argv[1];
bool a = false, d = false, f = false, l = false, h = false;
vector<string> files = vector<string>(); // holds the files in a directory
vector<string> paths = vector<string>(); // holds the paths
vector<dirls> options = vector<dirls>(); // holds multiple objects and their option flags
while ((opt = getopt(argc, argv, "adflh")) != -1)
{
switch (opt)
{
case 'a':
a = true;
break;
case 'd':
d = true;
break;
case 'f':
f = true;
break;
case 'l':
l = true;
break;
case 'h':
h = true;
break;
case '?': /* error - unknown option */
exit(0);
break;
default:
break;
}
if (argv[optind][0] != '-') // ISSUE?
options.push_back(dirls(a, d, f, l, h));
}
if (options.empty())
options.push_back(dirls(a, d, f, l, h));
for (int i = optind; i < argc; i++)
{
paths.push_back(argv[i]);
}
while (paths.size() < options.size())
{
paths.push_back(".");
}
for (int i = 0; i < paths.size(); i++)
{
cout << "paths are: " << paths[i] << " ";
}
return 0;
}
【问题讨论】:
-
optind在哪里定义?它有什么价值?什么改变了它的价值?它没有显示在您的代码中。 -
你已经在这个网站上提问一年了;没有人告诉你minimal complete examples?尝试简化该代码,删除功能和机制,看看错误何时消失;向我们展示你能找到的最简单的代码示例,该示例应该可以工作,但不能。
-
在这种情况下没有下一个值,
optind是刚刚超过argv末尾的元素的索引,并且您正在尝试读取该元素。您可以检查argc以防止出现此错误。 -
optind是getopt变量,用于保存 argv 中要处理的下一个元素的索引。 -
不,因为
&&的左侧参数在右侧之前评估。我认为if (optind < argc && argv[optind][0] != '-')会起作用,但我会在将其与其他代码集成之前对其进行彻底测试。
标签: c++ command-line-arguments getopt