gpt4 book ai didi

c - 从 C 中的命令行参数打开文件

转载 作者:太空狗 更新时间:2023-10-29 17:16:57 25 4
gpt4 key购买 nike

我希望我的 C 程序要求用户键入他们想要打开的文件的名称,并将该文件的内容打印到屏幕上。到目前为止,我正在学习 C 教程并拥有以下代码。但是当我执行它时,它实际上不允许我输入文件名。 (我得到“按任意按钮继续”,我正在使用代码块)

我在这里做错了什么?

#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[] ) 
{
char filename[100];
printf("Enter the file name: \n");
scanf("%s", filename);

...
FILE *file = fopen( filename, "r" );

关于c - 从 C 中的命令行参数打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9449295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com