命令行错误

标签 c linux

下面的代码应该逐字符读取文本文件并计算它们出现的频率。但是,在 Linux 命令行上,它会编译,并且当我尝试通过命令 ./program<file.txt 运行它时它显示

useage: huffman <filename>

我不知道错误是什么。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int count[26];
int main(int argc, char ** argv)
{
  unsigned char c;
  FILE * file;
int i;

  if ( argc != 2 ) {
    fprintf(stderr, "Useage: huffman <filename>\n");
    exit(1);        // exit with error code
  }

  file = fopen(argv[1], "r");
  assert( file != NULL );
c = fgetc(file);
  while( !feof(file) ) {
   c = fgetc(file);
   count[c-'a']++;
}
for(i=0; i<26; i++)
printf("count[%c]=%d\n",65+i,count[i]);
   fclose(file);
return 0;

最佳答案

当你执行它时

$ ./program < file.txt

您正在使用参数调用该程序,并将其标准输入流设置为从file.txt读取。因此,main 中的 argc 为 1,并且您会收到针对这种情况放置的错误消息。

要解决这个问题,您可以

  • 按预期运行程序(无需 shell 重定向)

    $ ./program file.txt
    
  • 或者修改您的程序,以便在不带参数调用时从标准输入读取。然后可以以任何一种方式调用它。

许多 POSIX 命令使用这样的约定:如果在没有文件名的情况下调用,它们将从标准输入中读取。例如,

$ cat file.txt

输出file.txt的内容,同时

$ cat

鹦鹉会回应你输入的所有内容。

要实现这一点,您需要这样的东西。

FILE * file = NULL;
if (argc == 1)
  {
    file = stdin;
  }
else if (argc == 2)
  {
    file = fopen(argv[1], "r");
    if (file == NULL)
      {
        fprintf(stderr, "error: %s: %s: %s\n",
                "cannot read file", argv[1], strerror(errno));
        return EXIT_FAILURE;
      }
  }
else
  {
    fprintf(stderr, "error: %s\n", "too many arguments");
    return EXIT_FAILURE;
  }
assert(file != NULL);  /* we have made this sure */

关于命令行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33983728/

相关文章:

C编程数组有帮助吗?

c - 在递归中使用后增量

linux - 将命令更改为不 fork 和耗尽资源的命令

c - 使用静态库链接、编译和运行 C 程序

c - 通过递归调用 make 来构建依赖关系?

python-3.x - 为什么我的 crontab -e 没有运行我的 python 脚本?

c - 有没有办法在运行 Linux 或 Windows 的台式计算机上使用 C 中的 "test"关键字来实现 "volatile"?

c - 使用具有不同路径名的 Makefile 构建 Linux 内核模块

c++ - 编译时检查右移是否是有符号类型的算术

linux - 适合新 Ruby on Rails 开发人员的最佳 Linux 截屏视频学习系列?