开发者

Using read() system call of UNIX to find the user given pattern

I am trying to emulate grep pattern of UNIX using a C program( just for learning ). The code that i have written is giving me a run time error..

#include <fcntl.h>
#include <stdio.h>
#include <string.h>

#define MAXLENGTH 1000
char userBuf[MAXLENGTH];

int main ( int argc, char *argv[])
{
        int numOfBytes,fd,i;


        if (argc != 2)
                printf("Supply correct number of arguments开发者_开发百科.\n");
                //exit(1);

        fd =open("pattern.txt",O_RDWR);

        if ( fd == -1 )
                printf("File does not exist.\n");
                //exit(1);

        while ( (numOfBytes = read(fd,userBuf,MAXLENGTH)) > 0 )
                ;

        printf("NumOfBytes = %d\n",numOfBytes);

        for(i=0;userBuf[i] != '\0'; ++i)
        {
                if ( strstr(userBuf,argv[1]) )
                        printf("%s\n",userBuf);
        }

}

The program is printing infinitely, the lines containing the pattern . I tried debugging , but couldn't figure out the error. Please let me know where am i wrong.,

Thanks


Say the string is "fooPATTERN". Your first time through the loop, you check for the pattern in "fooPATTERN" and find it. Then your second time through the loop, you check for the pattern in "ooPATTERN" and find it again. Then your third time, you check for the pattern in "oPATTERN" and find it again.

Since you're doing this to learn, I won't tell you much more. You can decide how best to solve it. There are at least two fundamentally different ways you could solve it. One is to do less on each pass of the loop to ensure you only find it once. The other is to make sure your next pass of the loop is past any pattern that was found.

One thing to think about: If the pattern is 'oo' and the string is 'ooo', how many patterns should be found? 1 or 2?


  1. The 'read' does not delimit the data with a null character.
  2. The while loop should encompase the for loop - it doesn't


First, you shouldn't be using raw Unix i/o with open and read if you're just learning C. Start with standard C i/o with fopen and fread/fscanf/fgets and so forth.

Second, you're reading in successive pieces of the file into the same buffer, overwriting the buffer each time, and only ever processing the last contents of the buffer.

Third, nothing guarantees that your buffer will be zero-terminated when you read into it with read(). In fact, it usually won't be.

Fourth, you're not using the i variable in the body of your loop. I can't tell exactly what you were shooting for here, but doing the same thing on the same data umpteen thousand times surely wasn't it.

Fifth, always compile with the fullest warning settings you can abide -- at lest -Wall with GCC. It should have complained that you call read() without including <unistd.h>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜