Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <signal.h>
- #include <string.h>
- #include <sys/wait.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <errno.h>
- #define BUFFER 1500
- #define READ 0
- #define WRITE 1
- int main(int argc, char* argv[]){
- char strFgets[BUFFER], wordsPath[BUFFER], temp[BUFFER], text[BUFFER];
- char file[BUFFER];
- int pid,fd[2];
- sprintf(file, "%s/words.txt", argv[1]);
- sprintf(temp, "%s/temp%s.txt", argv[1], argv[2]);
- char *number = malloc(strlen(argv[2]) + 1);
- if (number == NULL){
- exit(1);
- }
- strcpy(number, argv[2]);
- char *dot = strrchr(number, '.');
- *dot = '\0';
- int linenumber;
- int myPipe[2];
- //Open words files
- FILE *words;
- words = fopen(file, "r");
- //check if file exist
- if (words == NULL){
- perror("words.txt");
- exit(1);
- }
- fclose(words);
- char* outputFilename = malloc(strlen(argv[2]) + 1);
- strcat(outputFilename, number);
- strcat(outputFilename, ".sw");
- FILE * tempFile = fopen(outputFilename, "w");
- if (tempFile == NULL){
- perror("temp.txt");
- exit(1);
- }
- //creating pipes
- if (pipe(myPipe) == -1)
- {
- fprintf(stderr, "Error creating pipes.\n");
- exit(1);
- }
- if (pid > 0)
- {
- close(myPipe[WRITE]);
- wait(NULL);
- while ((fgets(text, BUFFER, words)) != NULL)
- {
- char* line = readline(myPipe[READ]);
- while (line != '\0')
- {
- if (sscanf(line, "%d:%s", &linenumber, text) > 0)
- {
- fprintf(tempFile, "%s : %s-%d\n", text, number, linenumber);
- }
- line = readline(fd[READ]);
- }
- }
- close(myPipe[READ]);
- }
- else if (pid == 0)
- {
- dup2(myPipe[WRITE], STDOUT_FILENO);
- close(myPipe[READ]);
- execlp("grep", "grep", "-w", "-o", "-n", "-f", file, temp, NULL);
- perror("grep");
- exit(1);
- }
- else // fork failed
- {
- }
- fclose(tempFile);
- return 0;
- }
- char* readline(int fd)
- {
- char string[1024];
- char currentByte;
- int i = 0;
- while (read(fd, ¤tByte, 1) > 0)
- {
- if (currentByte == '\n' || currentByte == '\0')
- {
- break;
- }
- string[i++] = currentByte;
- }
- string[i] = '\0';
- return string;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement