在C语言中使用命令行参数打开文件

8
我希望我的C程序要求用户输入要打开的文件名,并将该文件的内容打印到屏幕上。我正在学习C教程,目前已经有了以下代码。但是当我执行它时,实际上并没有让我输入文件名。(我得到了“按任意键继续”的提示,我正在使用CodeBlocks)
我在这里做错了什么?
#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;
}

6
如何就作业问题提问:不要说“帮我写这个程序”,而是说“我已经做到这一步遇到了难题”。 - Bob Kaufman
5个回答

5
这将从标准输入读取文件名。也许您只想在命令行中未提供文件名时才这样做。
int main ( int argc, char *argv[] ) 
{ 
    char filename[100];
    printf("Enter the file name: \n"); 
    scanf("%s", filename);

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

4
如果您想从提示框中读取用户输入,可以使用scanf()函数。要解析命令行参数,可以在命令行中输入它们,例如:
myprogram myfilename

不仅仅是输入,而是要使用
myprogram

预计会有提示。当您的程序启动时,myfilename 将出现在 argv 数组中。

因此,首先要删除 printf( "Enter the file name:" ) 提示。假设您在命令行上以 myprogram 之后的第一个参数输入文件名,则文件名将位于 argv[ 1 ] 中。


4
你混淆了命令行参数和用户输入。
当你使用命令行参数时,你在执行程序的同时传递参数。例如:
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]

啊!你是对的,我把它们搞混了。感谢你澄清了这个问题! - TylarBen

2

0
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[] )
{
    char filename[50];
    printf("Enter the Filename : ");
    scanf("%s",&filename);
    char line[50];
    FILE *fp = fopen( filename, "r");
   
    if (fp == NULL)
    {
        printf("File opening Unsuccessful\n");
        exit(1);
    }
    while (fgets(line , 30 , fp) != NULL)
    {
        strrev(line);
        printf(line);
    }
   fclose(fp) ;

   return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接