试图从命令行打开文件

Trying to open a file from command line

本文关键字:文件 命令行      更新时间:2023-10-16

,所以我想编写一些像命令行中的type一样起作用的代码
含义当我编写文本文件名时,它显示了它的内容。
我写了这篇文章:

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 existsn";
        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>

在使用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 */
}