更新时间:2023-11-17 23:43:52
David Warner写道:
David Warner wrote:
问候!
我需要写一些C代码将在从stdin读取或从argv获取文件名之间决定并处理它。
程序需要像所有典型的unix实用程序一样工作
要处理的文件是从管道/流或argv提供的。
lp,tr,grep等实用工具。
所以,当命令:
cat filename | grep -i> filename2
grep -i filename> filename2
执行,这就像我需要的programmtic接口。
我已经尝试了从getc,getchar,read,gets,
等我能想到的一切一切都行不通。我在返回值上测试EOF或NULL
并且程序只是在终端读取时挂起。所以,命令:
cat filename | testprogram -dvalue
挂在stdin的阅读上,我从来没有测试过EOF。
我缺少什么?
Greetings!
I need to write some C code that will decide between either reading from
stdin or take a file name from argv and process it.
The program needs to work like all of the typical unix utilities where
the file to process is either provided from a pipe/stream or argv.
Utilities like lp, tr, grep, etc.
So, when the command:
cat filename | grep -i > filename2
or
grep -i filename > filename2
executes, this acts like the programmtic interface i need.
I have tried everything I can think of from getc, getchar, read, gets,
etc. which all did not work. I test for EOF or NULL on the return values
and the program just hangs on a terminal read. So, the command:
cat filename | testprogram -dvalue
hangs on the reading from stdin and I never get to test for EOF.
What am i missing?
>
可能你可以显示你的代码,看看有什么遗漏。这个工作。
Probably you can show your code to see what''s missing. This one works.
cat simplecat.c
#include< stdio.h>
#include< stdlib.h>
#define BUF_SIZE 100
int main(int argc,char ** argv)
{char buf [BUF_SIZE + 1];
FILE * inp;
if(argc == 2)
{inp = fopen(argv [1]," r");
if(!inp)
{return EXIT_FAILURE;
}
}
其他
{inp = stdin;
}
while(fgets(buf,sizeof buf,inp))
{printf("%s",buf);
}
fclose(inp);
返回EXIT_SUCCESS;
}
ishs
cat simplecat.c
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 100
int main(int argc, char ** argv)
{ char buf[BUF_SIZE + 1];
FILE * inp;
if(argc == 2)
{ inp = fopen(argv[1], "r");
if(!inp)
{ return EXIT_FAILURE;
}
}
else
{ inp = stdin;
}
while(fgets(buf, sizeof buf, inp))
{ printf("%s", buf);
}
fclose(inp);
return EXIT_SUCCESS;
}
ishs
>
在文章< da **************************** @ corp.supernews.com>,
David Warner< da ****** @ westbase.com>写道:
In article <da****************************@corp.supernews.com >,
David Warner <da******@westbase.com> wrote:
我需要编写一些C代码来决定从stdin读取或从argv获取文件名并进行处理。
我已经尝试了从getc,getchar,read,gets,
等我能想到的一切。一切都行不通。我在返回值上测试EOF或NULL
并且程序只是在终端读取时挂起。
I need to write some C code that will decide between either reading from
stdin or take a file name from argv and process it. I have tried everything I can think of from getc, getchar, read, gets,
etc. which all did not work. I test for EOF or NULL on the return values
and the program just hangs on a terminal read.
通常要做的就是看看是否存在''文件名参数
如果没有,则从stdin读取。尝试阅读是没用的,因为
stdin上总会有文件或终端(对于典型的
操作系统)。
- Richard
The usual thing to do it to see whether there''s a filename argument
and read from stdin if there isn''t. Trying to read is useless, since
there will always be either a file or a terminal on stdin (for typical
operating systems).
-- Richard