Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

usage of strstr();

2 views
Skip to first unread message

Lincon Xue

unread,
Nov 27, 2003, 8:09:50 PM11/27/03
to

I want to handle a file in memory. This file is about 1.2M bytes. So I read the whole file in the memory . There is a special string in the file. When I use strstr() this special string , the debugger returns null . I want to know how long a tring the strstr() can to search.
the simple code is here:

#define specialstr "anystring"
#define _1M 1024*1024
char filedata[2*_1M];

void main(void,void)
{
FILE * fp;
char * spstrpos;
fp=fopen("path:file","rb");
fread(filedata,2*_1M,1,fp);
spstrpos=strstr(filedata,specialstr);

}

Any problem in it?
Thanks in advance!

Ed Mulroy [TeamB]

unread,
Nov 27, 2003, 10:34:03 PM11/27/03
to
While the array really should be allocated at runtime with malloc or if
using C++ with new, I copied what you showed and filled in the missing
parts. There was no problem finding the string in the file.

----------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define _1M 1024*1024
#define INSERT_POS (_1M + 32768)

char filedata[2*_1M];
const char filename[] = "bigtemp.tmp";
const char specialstr[] = "anystring";

int main()
{
FILE *fp;
char *spstrpos;
int i;

printf("Creating file ...");
fp = fopen(filename, "wb");

if (!fp)
{
printf("Could not open file\n");
return 0;
}

for (i = 0; i < (_1M + _1M); ++i)
{
if (i == INSERT_POS)
{
printf("\nInserting string at position %d ...", INSERT_POS);
fputs(specialstr, fp);
}
else
{
fputc((rand() % 27) + 'A', fp);
}
}

printf("\n");
fclose(fp);
fp = fopen(filename, "rb");

if (!fp)
{
printf("Could not open file\n");
return 0;
}

printf("\nReading file ...");
fread(filedata, sizeof(filedata), 1, fp);
spstrpos = strstr(filedata, specialstr);

if (!spstrpos)
{
printf("\nString not found\n");
}
else
{
printf("\nString found at position %d\n", (spstrpos - filedata));
}

fclose(fp);
return 0;
}

----------------------------------

. Ed

> Lincon Xue wrote in message
> news:3fc6ae6e$1...@newsgroups.borland.com...

JD

unread,
Nov 28, 2003, 7:22:55 AM11/28/03
to

"Lincon Xue" <xueyon...@zcom.unimis.com> wrote:
> [...] There is a special string in the file.

You should note that strstr() will not search past NULL
characters so if the file does has NULL characters you'll run
into a problem. Additionally, you should ensure that the file
in memory is NULL terminated to prevent a potential infinate
loop.

~ JD

Frank Birbacher

unread,
Nov 28, 2003, 5:31:40 PM11/28/03
to
Hi!

Lincon Xue wrote:
> #define specialstr "anystring"
> #define _1M 1024*1024
> char filedata[2*_1M];

You should not use "_1M". Everything beginning with an underscore "_" is
reserved for C++. However a trailing underscore is ok, like "MB_".

#define MBYTE 1024*1024

Frank

0 new messages