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 */
}