0

我想给用户指定一个文件的选项(这里是ground_truth_filename)。如果他没有指定选项,我想对默认文件名做出假设。

但是,即使我像在主程序中那样初始化它,我也无法检查ground_truth_filename是还是零。如果参数由用户传递,我将分配给该参数。但是检查给了我一个断言错误。NULL0ground_truth_filenameground_truth_filename == 0

任何帮助将不胜感激。

int processFile(const char *filename, 
                YAML::Emitter &out_yaml, 
                char *ground_truth_filename)
{   
    std::cout << "Here" << std::endl;

    if (ground_truth_filename == 0)
        sprintf(ground_truth_filename,"%s.yaml",filename);        

    std::ifstream imgstrm(filename, std::ios::binary | std::ios::in);

    if (imgstrm.bad() || !imgstrm.is_open())
    {
        fprintf(stderr, "Failed to open file: %s\n", filename);
        return FILE_ERROR;
    }

    // get ground truth
    std::ifstream ground_truth_stream(ground_truth_filename);

    if (!ground_truth_stream.is_open()) 
    {
        fprintf(stderr, "Failed to open file: %s\n", ground_truth_filename);
        return FILE_ERROR;
    }
}

这是函数的调用方式。也许我应该初始化 ground_truth_filename = '\0'?

char *ground_truth_filename = 0;
for (int i = 1; i + 1 < argc; i += 2) {
            if (!strcmp(argv[i], "--snapshot-markup")) {
                ground_truth_filename = argv[i + 1];
                markupFlag = true;
            }
        }
processFile(filename, out_yaml, ground_truth_filename)
4

2 回答 2

1

的第一个参数sprintf必须是指向足够大以保存输出的缓冲区的指针。指向较小字符缓冲区的NULL指针或指针(例如字符串文字“”)将导致崩溃。

可行的代码是:

char buf[256];

if (ground_truth_filename == NULL) {
   int charsneeded = snprintf(buf,sizeof(buf),"%s.yaml",filename);
   if (charsneeded >= sizeof(buf)) {
     return FILE_ERROR; // filename too long
   }
   ground_truth_filename = buf;
}

关键是这buf让新事物filename在记忆中占有一席之地。字符串需要那个。

编辑:添加了 charsneeded 以保护您免受文件名过长作为安全措施。如果您确实需要它,请改为动态分配 buf。

于 2013-02-12T18:38:14.593 回答
0

您需要先分配 ground_truth_filename,然后才能将字符复制到其中。

 if (ground_truth_filename == 0)
  {
    int length = strlen(filename) + strlen(".yaml") + 1;
    ground_truth_filename = new char[length];
    sprintf(ground_truth_filename,"%s.yaml",filename);   
  }
于 2013-02-12T18:37:25.463 回答