Link to home
Start Free TrialLog in
Avatar of libin_v
libin_vFlag for India

asked on

implement ls | wc in C code

I wanted to write a c code to implement
ls | wc
say ls and wc is in /bin.

I know how to redirect a file eg ls > list.txt.
I wanted to know if ls | wc works with the same logic as redirection? If yes, please give me the code.

I also heard that we can use the pipe().
Please implement ls | wc using pipe() in C.
Avatar of Mysidia
Mysidia
Flag of United States of America image

If you just want to invoke the command from within your C program and get the result,
calling pipe() directly seems way overkill.   I would tend to say use popen() and rely on
the implementation of redirection provided by the shell.

What are you trying to accomplish: i.e. why do you want to implement
such an esoteric command like "ls |wc" using pipe() in C?

I think it might be better to just enumerate the files with opendir() readdir() and count
the lengths of filename strings, and ignore /bin/ls and /bin/wc  entirely

to accomplish whatever your program needs this information for: certainly it will win you
more in terms of speed than doing redirection and pipe() will
It is the same situation for ls

ls > list.txt       Redirects to a file
ls | wc            Redirects to another application (pipe)

From 'ls' side, it just print all output to the standard output (stdout), normally the console.

About wc side, this applications take its input from standard input (stdin), normally the console. So you can invoke wc this way:
wc <list.txt       Input from a file
ls | wc             Input from an application

So, in conclusion, there is not a special handling for these operations, just have to input and output from/to console with simple printf() and scanf() or fread()/fwrite() operations to/from stdout/stdin.

Good luck,
Jaime.
Avatar of libin_v

ASKER

Thank PST,
But want to do it with ls and wc.

Thanks Jaime.
As I told U I do want how to redirect to/from a file. But I want to implement to both ls & wc, since both are new process(using fork).
If you want to avoid synchonization issues between process you can do this:

1st phase:
ls >temp.txt

2nd phase:
wc <temp.txt >result.txt
Avatar of jkr
If you basically want to count the files in a directory, you could use

#include <sys/types.h>
#include <dirent.h>

unsigned int countfiles(char* pPath) {

unsigned int count = 0;
struct dirent* pEnt = NULL;
int n;
DIR* pDir = opendir(pPath);

while(pEnt = readdir(pDir)) {

    if ( !strcmp(pEnt->d_name, ".") && !strcmp(pEnt->d_name, "..")) count++; // skip "." and ".."
}

closedir(pDir);

return count;
}

}
Avatar of libin_v

ASKER

Thanks Guys,
But listen I need to demonstrate how piping works in a shell. The code below works fine, but since popen() deals with commands same as the system(), I am not able to do job control as sending to foreground or background.

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>

int main()
{
      FILE *stream;

      stream = popen ("//bin//ls", "w");
      pclose(stream);
      stream = popen ("//bin//cat", "r");
      pclose(stream);

      /* cannot control the cat process;
            eg: ls | cat&
      */
}

I have written a code for piping, which I can later inco-operate the job control (as bcakground or foreground). But when executing, it gives me errors as "bad file descriptor". Please rectify this code.

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>

int main()
{
      pid_t pid;
      int status;
      int some[2];

      if( pipe (some) == 0 )
      {
            pid = fork();
            if( pid == 0 )
            {
                  close (some[0]);
                  fclose (stdout);
                  stdout = fdopen (some[1], "w");
                  execl ("//bin//ls", "ls", NULL);
                  _exit(0);
            }
            else
            {
                  waitpid (pid, &status, 0);
                  pid = fork();
                  if( pid == 0 )
                  {
                        close (some[1]);
                        fclose (stdin);
                        stdin = fdopen (some[0], "r");
                        execl ("//bin//cat", "cat", NULL);
                        _exit(0);
                  }
                  else
                     waitpid (pid, &status, 0);
            }
      }
}
ASKER CERTIFIED SOLUTION
Avatar of Mysidia
Mysidia
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of grg99
grg99

Remember of course that file names are not what wc counts!