在C中从命令行参数打开文件
我希望我的C程序要求用户键入他们想要打开的文件的名称,并将该文件的内容打印到屏幕上。我正在学习C教程,到目前为止,我有以下代码。但是当我执行它时,它实际上不允许我输入文件名。(我得到“按任意按钮继续”,我正在使用代码块) 我做错了什么在C中从命令行参数打开文件,c,fopen,C,Fopen,我希望我的C程序要求用户键入他们想要打开的文件的名称,并将该文件的内容打印到屏幕上。我正在学习C教程,到目前为止,我有以下代码。但是当我执行它时,它实际上不允许我输入文件名。(我得到“按任意按钮继续”,我正在使用代码块) 我做错了什么 #include <stdio.h> int main ( int argc, char *argv[] ) { printf("Enter the file name: \n"); //scanf if ( argc !=
#include <stdio.h>
int main ( int argc, char *argv[] )
{
printf("Enter the file name: \n");
//scanf
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
/* Read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
return 0;
}
#包括
int main(int argc,char*argv[])
{
printf(“输入文件名:\n”);
//斯坎夫
如果(argc!=2)/*argc应为2以正确执行*/
{
/*我们打印argv[0],假设它是程序名*/
printf(“用法:%s文件名”,argv[0]);
}
其他的
{
//我们假设argv[1]是要打开的文件名
FILE*FILE=fopen(argv[1],“r”);
/*fopen在失败时返回0,即空指针*/
如果(文件==0)
{
printf(“无法打开文件\n”);
}
其他的
{
int x;
/*每次从文件中读取一个字符,在EOF处停止,这
指示文件的结尾。请注意,习惯用法“assign”
对于变量,请选中下面使用的值“因为
赋值语句的计算结果为指定的值*/
而((x=fgetc(文件))!=EOF)
{
printf(“%c”,x);
}
fclose(文件);
}
}
返回0;
}
如果要从提示符读取用户输入,可以使用scanf()
函数。要分析命令行参数,请在命令行中键入它们,如中所示:
myprogram myfilename
而不仅仅是打字
myprogram
并期待得到提示<当程序启动时,code>myfilename将位于argv
数组中
因此,首先删除
printf(“输入文件名:”)
提示。文件名将位于argv[1]
中,假设您在命令行的myprogram
之后输入它作为第一个参数。这将从文件名的stdin中读取。也许您只想在文件名未作为命令行的一部分提供时执行此操作
int main ( int argc, char *argv[] )
{
char filename[100];
printf("Enter the file name: \n");
scanf("%s", filename);
...
FILE *file = fopen( filename, "r" );
您将命令行参数与用户输入混为一谈 使用命令行参数时,执行程序并同时传递参数。例如:
ShowContents MyFile.txt
相反,读取用户输入时,首先执行程序,然后提供文件名:
ShowContents
Enter the file name: MyFile.Ttxt
您的程序已读取第一个参数argv[1],并将其作为要打开的文件名。要让程序读取用户输入,请执行以下操作:
char str[50] = {0};
scanf("Enter file name:%s", str);
然后文件名将位于
str
,而不是argv[1]
,这是因为IDE没有将filename参数传递给程序。看看这个。+1。这是如何问一个关于家庭作业的问题。“我走了这么远,遇到了一个路障”,而不是“为我写这个程序”。啊!你是对的,我把它们混在一起了。为清理这些干杯!