Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 试图从命令行打开文件_C++_Command Line - Fatal编程技术网

C++ 试图从命令行打开文件

C++ 试图从命令行打开文件,c++,command-line,C++,Command Line,因此,我想编写一些类似于命令行中的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 exists\n";

因此,我想编写一些类似于命令行中的
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 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;
  }
intmain(intargc,char*argv[])
{
文件*t;
t=fopen(argv[1],“r”);//尝试从命令行打开文件
如果(t==NULL){

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

在尝试使用参数之前,最好检查是否有足够的参数。要使用
argv[1]
argc>1
必须为真。这正是问题所在。@internetaussie什么是“expression”?我发现很难相信这就是你收到的消息。@Arof:为什么你不给它文件名就希望它工作?奇怪的问题!是的,因为有人会对消息撒谎,信不信由你,这就是我得到的,谁在你的咖啡里撒尿?我显然在发布这个问题之前给了它文件名n!!!!@BoundaryPosition
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 */
}