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[]){
- //verificacao do numero de argumentos
- if (argc != 3) {
- printf("Numero errado de argumentos.\n");
- printf("Usage: %s <directory> <filename>\n", argv[0]);
- exit(1);
- }
- char strFgets[BUFFER], wordsPath[BUFFER], temp[BUFFER], text[BUFFER];
- char file[BUFFER];
- 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 myPipe[2];
- //abrir o ficheiro das palavras a procurar
- FILE *words;
- words = fopen(file,"r");
- //verifica se o ficheiro existe
- 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);
- }
- //criar pipes
- if (pipe (mypipe) == -1){
- fprintf(stderr, "Erro ao criar pipes.\n");
- exit(1);
- }
- //pai
- if(pid > 0){
- close(mypipe[WRITE]);
- //enquanto o ficheiro onde se encontram as palavras a procurar nao termina,
- //continua a procura as palavras no ficheiro de texto passado como 2ΒΊ argumento
- int read=1;
- while( (fgets(text, BUFFER, words))!= NULL){
- text[strlen(text)-1]='\0';
- char buff[1024];
- read =read(mypipe[READ],buff,1023);
- while(read != 0){
- while(buff[read] != '\0'){
- char *doubleDots = strchr(text, ':');
- if (doubleDots != NULL){
- char* line =readline(mypipe(read));
- fprintf(tempFile, "%s : %s-%s\n", doubleDots + 1, number, text);
- }
- }
- }
- }
- //close(mypipe[READ]);
- wait(NULL);
- }
- else{
- dup2(mypipe[WRITE], STDOUT_FILENO);
- close(mypipe[READ]);
- execlp("grep", "grep", "-w", "-o", "-n", "-f", file, temp, NULL);
- perror("grep");
- exit(1);
- }
- 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