下面的代码应该逐字符读取文本文件并计算它们出现的频率。但是,在 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/