从C中的命令行参数打开文件 [英] Opening a file from command line arguments in C

查看:93
本文介绍了从C中的命令行参数打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的C程序要求用户键入要打开的文件的名称,然后将该文件的内容打印到屏幕上.到目前为止,我正在C教程中工作,并且具有以下代码.但是当我执行它时,它实际上不允许我输入文件名.(我得到的是按任意按钮继续",我正在使用代码块)

I want my C program to ask the user to type the name of the file they want to open and print the contents of that file to the screen. I am working from the C tutorial and have the following code so far. But when I execute it, it doesn't actually allow me to enter the file name. (I get the 'press any button to continue', I am using 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;
}

推荐答案

如果要从提示中读取用户输入,则可以使用 scanf()函数.要解析命令行参数,您可以在命令行中输入它们,如下所示:

If you want to read user input from a prompt, you would use the scanf() function. To parse command line parameters, you would type them at the command line, as in:

myprogram myfilename

不仅仅是输入

myprogram

,希望得到提示.程序启动时, myfilename 将位于 argv 数组中.

and expecting to be prompted. myfilename would be in the argv array when your program starts.

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

So, start by removing the printf( "Enter the file name:" ) prompt. The filename would be in argv[ 1 ] assuming you entered it as the first parameter after myprogram on your command line.

这篇关于从C中的命令行参数打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆