[comp.unix.questions] C to Shell -- Summary and another question

rose@baby.swmed.utexas.edu (Rose Oguz) (06/01/90)

A few people asked me to post the solution to my interfacing C code to a 
shell script question.  The consenus seems to be to use popen().  The 
syntax follows:

	FILE *popen(command, type)
	char *command, *type;

	command is a shell command line
	type is I/O mode: r or w

So, I used
	char f_names[20];
	char *ret_stat;
	long stat;
	FILE *fp
	...
	if ((fp = popen("ls *c", "r") != NULL)
	{
		while ((stat=fscanf(fp, "%s", f_names)) != EOF)
		{
			...
		}
	}
	pclose(fp);


I also changed the fscanf line to

		while ((ret_stat=fgets(f_names, 2, fp)) != NULL)


Neither seems to work.  A file pointer is returned, but the while loop
is never executed.  For the fscanf, -1 (EOF) is returned and for the
fgets, NULL (also, EOF since I opened the file with popen) is
returned.  I'm running this in my source directory; so, I know that
files exist.  What am I doing wrong?  Any ideas?

subbarao@phoenix.Princeton.EDU (Kartik Subbarao) (06/01/90)

In article <23498@adm.BRL.MIL> rose@baby.swmed.utexas.edu (Rose Oguz) writes:
>
>So, I used
>	char f_names[20]; /* Make this 21 */
>	char *ret_stat;
>	long stat;
>	FILE *fp;
>	...
>	if ((fp = popen("ls *c", "r") != NULL) 
  	/* Need an extra ')' here ---^ */
	{
 	/* Ugly fscanf code deleted */
>	  while ((ret_stat=fgets(f_names, 2, fp)) != NULL)
>		                      /* ^^^ 2?! Don't you mean 20? */
	}
>	pclose(fp);
>
>
>Neither seems to work.  A file pointer is returned, but the while loop
>is never executed.  For the fscanf, -1 (EOF) is returned and for the
>fgets, NULL (also, EOF since I opened the file with popen) is
>returned.  I'm running this in my source directory; so, I know that
>files exist.  What am I doing wrong?  Any ideas?

I have no idea how this passed the compiling stage of your computer. The way
it looks now, its as if you are saying fp = (popen("ls *c", "r") != NULL),
because != has higher precedence than =. And so our compiler will gripe 
because you are trying to assign the value of int to a FILE *.

As to fgets, it should now work -- I hope you meant 20 instead of 2!


		-Just another popen() hacker,
	  	 Kartik


			
-- 
subbarao@{phoenix,bogey or gauguin}.Princeton.EDU -|Internet
kartik@silvertone.Princeton.EDU (NeXT mail)       -|	
subbarao@pucc.Princeton.EDU		          - Bitnet