Jump to content

[Help]Open Text File And Excute Certain Commnad

- - - - -

  • Please log in to reply
3 replies to this topic

#1
av01d3r

av01d3r

    Newbie

  • Members
  • Pip
  • 2 posts
someone please help me
I want to create software with the workings. my software open a file and read the contents therein, if the my software find a certain word in it then it will execute certain commands.
how do i make it
please help me
sorry if my english is bad because i'm from indonesia

#2
DRK

DRK

    Newbie

  • Members
  • PipPip
  • 10 posts
C code:
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
 
void findAndExecute(const char *filename, const char *word, const char *command)
{
 FILE *f;
 long size;
 char *buff;
 
 f = fopen(filename, "r");
 if (f != NULL)
 {
  fseek(f, 0, SEEK_END);
  size = ftell(f);
  fseek(f, 0, SEEK_SET);
  buff = malloc(size + 1);
  memset(buff, 0, size + 1);
  fread(buff, 1, size, f);
  fclose(f);
  if (strstr(buff, word) != NULL)
  {
   system(command);
  }
  free(buff);
 }
}


#3
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
I would add an opinion for the solution DRK posted above. Although it would work for most of the cases and explains the workings well. But

1. Why do you have to read the entire file first into memory to search a string? File can be very large and your malloc might fail at some point.

2. Even if it doesn't, it will take a long time reading complete file and THEN start searching.

Can't we read char by char or a fixed length string? The only thing we would need to keep track of is, if some part of the required string is matched and our currently read string terminated, we need to ensure it continues for the remaining part. It doesn't seem like a hard thing to do.
Today is the first day of the rest of my life

#4
DRK

DRK

    Newbie

  • Members
  • PipPip
  • 10 posts
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
 
void findAndExecute(const char *filename, const char *word, const char *command)
{
 FILE *f;
 int len, res;
 char *buff, c;
 
 f = fopen(filename, "r");
 if (f != NULL)
 {
  len = strlen(word);
  buff = malloc(len + 1);
  memset(buff, 0, len + 1);
  fread(buff, 1, len, f);
  while ((res = strcmp(buff, word)) != 0 && fread(&c, 1, 1, f) == 1)
  {
   buff[len] = c;
   memmove(buff, buff + 1, len);
   buff[len] = 0;
  }
  fclose(f);
  free(buff);
  if (res == 0)
  {
   system(command);
  }
 }
}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users