VOOZH about

URL: https://www.geeksforgeeks.org/c/sort-numbers-from-file-using-unix-pipes-in-c/

⇱ Sort Numbers from File Using Unix Pipes in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort Numbers from File Using Unix Pipes in C

Last Updated : 23 Jul, 2025

In this article, we will write a straightforward C program that sorts numerical data from a file using pipes and forks.The sorting process is carried out using the sort command and the execlp function of UNIX.

Working of the Program

  1. We need to include the following header files to use the relevant functions:
    1. #include <stdio.h>
    2. #include <string.h>
    3. #include <stdlib.h>
    4. #include <unistd.h>
    5. #include <sys/wait.h>
    6. #include <fcntl.h>
  2. The name of the file to be read will be taken as the command line argument.
  3. After that, we create a pipe and store the file descriptor for it in the fd[] array.
  4. Then we create another process using fork() call.
  5. In the child process, sort() system call is called for the file passed as a command line argument, and the data returned by the sort() call is sent to the pipe.
  6. In the parent process, the data is received and read using the buffer and is printed on the console.

C Program to Sort Numbers from File using Unix Pipes

Output

While running program, provide the file name you want to read,

./your_program_name [input file]

Now assume that your file contains the the following data

file.txt

2
84
321
684
321
84

Then the output will be

Data received through pipe:2
Data received through pipe:84
Data received through pipe:84
Data received through pipe:321
Data received through pipe:321
Data received through pipe:684
Comment