Sort Numbers from File Using Unix Pipes in C
Last Updated :
30 Jan, 2024
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
- We need to include the following header files to use the relevant functions:
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <fcntl.h>
- The name of the file to be read will be taken as the command line argument.
- After that, we create a pipe and store the file descriptor for it in the fd[] array.
- Then we create another process using fork() call.
- 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.
- 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
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#define buffer 1024
int main( int argc, char *argv[]) {
int id, fd[2];
char my_copy[buffer];
if (argc != 2) {
printf ( "Usage: %s <input_file>\n" , argv[0]);
exit (1);
}
if (pipe(fd) == -1) {
perror ( "Pipe creation failed" );
exit (2);
}
id = fork();
if (id == -1) {
printf ( "An error occurred with fork\n" );
exit (3);
}
if (id == 0) {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execlp( "sort" , "sort" , "-n" , argv[1], NULL);
perror ( "Error calling execl" );
exit (4);
} else {
close(fd[1]);
wait(NULL);
FILE *pipe_fd = fdopen(fd[0], "r" );
if (pipe_fd == NULL) {
perror ( "fdopen" );
exit (5);
}
while (( fgets (my_copy, sizeof (my_copy), pipe_fd)) != NULL) {
if ( strchr (my_copy, '\n' ) != NULL) {
printf ( "Data received through pipe:%s" , my_copy);
}
}
fclose (pipe_fd);
}
return 0;
}
|
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
Share your thoughts in the comments
Please Login to comment...