关于 `argv` 和使用命令行打开文件

About `argv` and opening a file with command line

我有这个代码:

#include <stdio.h>

int main ( int argc, char *argv[] )
{    
     FILE *file;
     int x;

     if ( argc != 2 )
           printf( "Use: %s file name", argv[0] );
     else {
            if ((file=fopen( argv[1], "r" ))== 0 ) 
            printf( “Couldn't open the file.\n" );
             else {
                          while (( x = fgetc( file ) ) != EOF)  printf( "%c", x );
                          fclose( file );
              }
      }
      return 0;
}

现在,有了这段代码,我如何从终端执行文件(在图片以及我的 NetBeans 配置上)。 http://i.stack.imgur.com/6WRh3.png

首先,最好替换你的语句(在你上面的程序中)

printf( “Couldn't open the file.\n" );

perror(argv[1]);

然后,只需在您的终端中编译您的程序,例如在那里输入类似于

的shell命令
gcc -Wall -g mysource.c -o myprog

(阅读更多关于 invoking GCC: the -Wall option asks for nearly all warnings and is very useful -so never miss it-; you could even add -Wextra to get even more warnings; the -g is asking for DWARF debugging information in the ELF 可执行文件的信息,让您以后可以使用 gdb

假设您的源代码在当前 working directory 中名为 mysource.c 的文件中(使用 pwd 命令查询当前目录, ls -al 列出它,和 cd 内置命令来更改它)

最后,运行 您的程序

./myprog sometestfile.txt

您可能想使用 debugger. Read first about GDB,也许可以试试

gdb ./myprog

(我猜您使用的是 Linux 或其他一些 POSIX 兼容的操作系统,并且使用 GCC 编译器)

阅读更多关于 perror(3), command line interface, shells, globbing, glob(7), PATH variable

稍后,您会希望在几个 translation units, having some common header file (to be #included in all of them). Then you'll use a builder like GNU make. You could use a good editor like emacs, some version control like git 等中制作一些更大的程序...

(您可能会意识到 NetBeans 不是很有用,因为您可以使用 您的 自己的 集合 工具;自由选择工具是值得的!)

PS。也许用更短更有效的 putchar(x); ...

替换 printf( "%c", x );