尝试从命令行打开文件

时间:2017-04-24 14:34:37

标签: c++ command-line

所以我想在命令行中编写一些与int main(int argc, char* argv[]) { FILE *t; t = fopen(argv[1], "r"); // tring to open file from command line if (t == NULL){ cout << "the file doesnt exists\n"; return 0; } else{ fseek(t, 0, SEEK_END); int size = ftell(t); fseek(t, 0, SEEK_SET); char* x = new char[size]; fread(x, size, 1, t); for (int i = 0; i<size; i++) { cout << x[i]; } delete[] x; } return 0; } 类似的代码 这意味着当我写文本文件名时,它会显示它的内容 我写了这个:

Exppression:file!=NULL <br>

我收到了Debug Assertion Failed Error

{{1}}

1 个答案:

答案 0 :(得分:2)

在使用argv中的参数之前,请确保满足您的需求:

if (argc > 1) {
    // We have enough args in argv, go for it
    t = fopen(argv[1], "r");
} else {
    /* do something else that doesn't need argv[1] i.e. ask the user */
}