473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Problem with string manipulation

Hi folks

I am trying to write a program which acts like a p2p server. When the
program starts it reads a file from whereit will read broadcast IP
address, port and another port number. Now I am trying skip the
comments and empty lines by saying if there is newline or # sign at the
first charecter of a line then to skip the line.But the problem is the
program is not working.

I am using the following code:

line = malloc(sizeof (char) *SIZE_OF_LINE);

while(fgets(line, SIZE_OF_LINE + 1, fp) != NULL)
{
i f(line[0] != '#' || line[0] != '\n')
{
fprintf(stderr,"i am here\n");
fprintf(stderr,"%s", line);
strcpy(tmpEntry, strtok(line, ":"));
strcpy(tmpValue, strtok(NULL, "\n"));
fprintf(stderr,"\t%s", tmpEntry);
fprintf(stderr,"\t: %s\n", tmpValue);
}
}

and the file the program is reading is:

################################################## ###########################
# P2P Conf File
#Please Don't modify this file as this is file is used to
#create all required sockets
# Author : Ahetesham Qazi
################################################## ###########################

Brodcast_IP:192.168.1.255
Brodcast_Port:30001
Comm_Port:30101

The program should skip the first seven lines but the problem it's not
skipping. and when it's trying to tokenize the first line and then
printing it it's giving me segmentation fault.

Any suggetion would be greatly appreciated
Thanks
Ahetesham Qazi

Oct 5 '06 #1
14 1735
aq***@inbox.com said:
if(line[0] != '#' || line[0] != '\n')
How many characters can you think of that will fail this condition?

Read it out loud. If this character is not a hash, OR it is not a newline...

So a hash PASSES the test because it is not a newline, and a newline PASSES
the test because it is not a hash.

You meant to use && rather than ||

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 5 '06 #2
>I am trying to write a program which acts like a p2p server. When the
>program starts it reads a file from whereit will read broadcast IP
address, port and another port number. Now I am trying skip the
comments and empty lines by saying if there is newline or # sign at the
first charecter of a line then to skip the line.
....
>I am using the following code:

line = malloc(sizeof (char) *SIZE_OF_LINE);

while(fgets(line, SIZE_OF_LINE + 1, fp) != NULL)
{
i f(line[0] != '#' || line[0] != '\n')
A newline is not equal to '#'.
A # is not equal to '\n'.
Another character is not equal to either.
In other words, the condition is always true.

Do you really want to use OR here?
Oct 5 '06 #3

Richard Heathfield wrote:
aq***@inbox.com said:
if(line[0] != '#' || line[0] != '\n')

How many characters can you think of that will fail this condition?

Read it out loud. If this character is not a hash, OR it is not a newline...

So a hash PASSES the test because it is not a newline, and a newline PASSES
the test because it is not a hash.

You meant to use && rather than ||

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Thanks for the solution. Actually this is a strictly predefined file.
So whithout the actual data
the only charecter can be at the start of the file is "#" or "\n"
Ahetesham Qazi

Oct 5 '06 #4
aq***@inbox.com said:
>
Richard Heathfield wrote:
>aq***@inbox.com said:
if(line[0] != '#' || line[0] != '\n')

How many characters can you think of that will fail this condition?

Read it out loud. If this character is not a hash, OR it is not a
newline...

So a hash PASSES the test because it is not a newline, and a newline
PASSES the test because it is not a hash.

You meant to use && rather than ||
Thanks for the solution. Actually this is a strictly predefined file.
So whithout the actual data
the only charecter can be at the start of the file is "#" or "\n"
Nevertheless, all characters, *including* hash and newline, will pass your
existing test, the one that is intended to filter them out. When you change
the || to && the filter will have the desired effect.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 5 '06 #5
aq***@inbox.com wrote:
Hi folks

I am trying to write a program which acts like a p2p server. When the
program starts it reads a file from whereit will read broadcast IP
address, port and another port number. Now I am trying skip the
comments and empty lines by saying if there is newline or # sign at the
first charecter of a line then to skip the line.But the problem is the
program is not working.

I am using the following code:

line = malloc(sizeof (char) *SIZE_OF_LINE);

while(fgets(line, SIZE_OF_LINE + 1, fp) != NULL)
Do not lie to fgets. You only have storage for
SIZE_OF_LINE chars, not SIZE_OF_LINE + 1.
Oct 5 '06 #6
aq***@inbox.com wrote:
line = malloc(sizeof (char) *SIZE_OF_LINE);
sizeof(char) is by definition 1, *always*, so this can be reduced to

line = malloc (SIZE_OF_LINE);
--
Nick Keighley

Oct 5 '06 #7
Nick Keighley said:
aq***@inbox.com wrote:
>line = malloc(sizeof (char) *SIZE_OF_LINE);

sizeof(char) is by definition 1, *always*, so this can be reduced to

line = malloc (SIZE_OF_LINE);
That's one perfectly sensible approach. Here's another:

line = malloc(SIZE_OF_LINE * sizeof *line);

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 5 '06 #8

aq***@inbox.com wrote:
line = malloc(sizeof (char) *SIZE_OF_LINE);
This would be a bit safer as: line = malloc( sizeof( *line ) );

while(fgets(line, SIZE_OF_LINE + 1, fp) != NULL)
similarly: while(fgets(line, sizeof( *line ), fp) != NULL)
if(line[0] != '#' || line[0] != '\n')
Several things amiss here:

(1) Are you sure if line[0] has been set? Yes, fgets() USUALLY puts
in a "\n", but not in every case.
You should do something like this first: : if( strlen(line) 0 ) {
....

(2) The tests are backwards.. It's more obvious if you write:

if( line[0] == '#' || line[0] == '\n' ) { /* ignore this line */ }
else { /* process it */
...
}

(3) What if the user accidentally types a space or tab, either leading
or trailing the line? Wouldnt hurt to handle these cases too.
(3) You're being awfully optimistic about what's in the file. I'd add
several tests to ensure that strtok finds what you expect, and the
length of the token doesnt overflow the destination. What you have
right now is an excellent way for somebody to crash or own your server
with a buffer overflow if they get write access to this file.

Oct 5 '06 #9
Ancient_Hacker said:
>
aq***@inbox.com wrote:
>line = malloc(sizeof (char) *SIZE_OF_LINE);

This would be a bit safer as: line = malloc( sizeof( *line ) );
Er, no it wouldn't.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 5 '06 #10
On 5 Oct 2006 04:10:04 -0700, "Ancient_Hacker" <gr**@comcast.net>
wrote:
>
aq***@inbox.com wrote:
>line = malloc(sizeof (char) *SIZE_OF_LINE);

This would be a bit safer as: line = malloc( sizeof( *line ) );
Since line appears to be a char* (see your note (2) below), this
allocates one byte. Safer perhaps but not usable.
>
>while(fgets(line, SIZE_OF_LINE + 1, fp) != NULL)

similarly: while(fgets(line, sizeof( *line ), fp) != NULL)
Why read only 1 byte of the line?
>
> if(line[0] != '#' || line[0] != '\n')

Several things amiss here:

(1) Are you sure if line[0] has been set? Yes, fgets() USUALLY puts
in a "\n", but not in every case.
It is pretty rare for fgets to put a \n in the first position of a
buffer. Usually happens when the line is empty.
>You should do something like this first: : if( strlen(line) 0 ) {
...

(2) The tests are backwards.. It's more obvious if you write:

if( line[0] == '#' || line[0] == '\n' ) { /* ignore this line */ }
else { /* process it */
...
}

(3) What if the user accidentally types a space or tab, either leading
or trailing the line? Wouldnt hurt to handle these cases too.
(3) You're being awfully optimistic about what's in the file. I'd add
several tests to ensure that strtok finds what you expect, and the
length of the token doesnt overflow the destination. What you have
right now is an excellent way for somebody to crash or own your server
with a buffer overflow if they get write access to this file.

Remove del for email
Oct 5 '06 #11

Richard Heathfield wrote:
Ancient_Hacker said:

aq***@inbox.com wrote:
line = malloc(sizeof (char) *SIZE_OF_LINE);
This would be a bit safer as: line = malloc( sizeof( *line ) );

Er, no it wouldn't.
Note to self: engage brain before typing.

What I shudda typed:

In general it's safer to use quantities that are closely correlated.

For example:

#define SZ 1000

typedef char String[ SZ ];
typedef String * StringPtr;

StringPtr p;

p = (StringPtr) malloc( sizeof( char ) * SZ ); // this is
correct, but a bit indirect

p = (StringPtr) malloc( sizeof( *p ) ); // this is a
whole lot more direct.

.... In the first malloc, everything is hunky-dorey, until soembody
changes the type of the string to 2-byte characters, then things go
blooey. Or someone changes SZ to StringSZ in the first two occurences,
but not the one in the malloc.

.... the second malloc is considerably less prone to blowing up, as
we're using the size of what p points to to initialize "p".

Now you can't always do this, and it does take a bit more typing and
static typedefs, but what price safety?

Oct 5 '06 #12
Ancient_Hacker said:

<snip>
>
#define SZ 1000

typedef char String[ SZ ];
EEK!! Naming an array of a particular (and rather low) size "String" is just
asking to confuse people.

String x; /* x is a String, but not a string! */

char foo[] = "I'm a string"; /* foo holds a string, but not a String! */
typedef String * StringPtr;
AARGH!! Hiding a pointer in a typedef!
StringPtr p;

p = (StringPtr) malloc( sizeof( char ) * SZ ); // this is
correct, but a bit indirect
The cast is unnecessary.
p = (StringPtr) malloc( sizeof( *p ) ); // this is a
whole lot more direct.
True, but the cast is still unnecessary.

<snip>
Now you can't always do this, and it does take a bit more typing and
static typedefs, but what price safety?
I prefer, where possible, to get my safety without compromising generality.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 5 '06 #13

Richard Heathfield wrote:
Ancient_Hacker said:

<snip>

#define SZ 1000

typedef char String[ SZ ];

EEK!! Naming an array of a particular (and rather low) size "String" is just
asking to confuse people.
>
AARGH!! Hiding a pointer in a typedef!

Sorry to see my conventions alarm you. Guess we'll have to disagree as
to what's best.
I prefer, where possible, to get my safety without compromising generality.
I prefer to have safety first, even if the straight-jacket chafes a
bit.

One can always resort to rambunction like: p = malloc( sizeof( foo ) *
bar ) if there is no alternative.

What really frosts my fritters is seeing lines like "bar = 32 + 400 +
4" when it really should be something like bar = sizeof( struct a ) +
sizeof( LongArrayType ) + sizeof( long );

Way too much of this code out there.

Oct 6 '06 #14
"Ancient_Hacker" <gr**@comcast.netwrites:
Richard Heathfield wrote:
>Ancient_Hacker said:
<snip>
>
#define SZ 1000

typedef char String[ SZ ];

EEK!! Naming an array of a particular (and rather low) size "String" is just
asking to confuse people.

AARGH!! Hiding a pointer in a typedef!

Sorry to see my conventions alarm you. Guess we'll have to disagree as
to what's best.
The typedef in question was
typedef String * StringPtr;

The fact that the name ends in "Ptr" means it's not *too* bad, but
using a typedef for a pointer still makes me uneasy. I would drop the
typedef and just use "String *" wherever you'd use "StringPtr".

For that matter, I probably wouldn't use a pointer to an array. It's
perfectly legal, of course, but I think a pointer to the first element
of the array is more idiomatic and more general. (If I really wanted
a pointer to the full array, I'd probably wrap it in a structure.)

And I certainly wouldn't use the name "String", for reasons I think
Richard has already discussed.
>I prefer, where possible, to get my safety without compromising generality.

I prefer to have safety first, even if the straight-jacket chafes a
bit.

One can always resort to rambunction like: p = malloc( sizeof( foo ) *
bar ) if there is no alternative.
Or, better:

p = malloc(bar * sizeof *p);

I'm assuming that bar is a count. I'm also assuming that p is of type
foo, something that I don't have to assume with the improved form.
What really frosts my fritters is seeing lines like "bar = 32 + 400 +
4" when it really should be something like bar = sizeof( struct a ) +
sizeof( LongArrayType ) + sizeof( long );

Way too much of this code out there.
Agreed wholeheartedly.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 6 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
by: zoro | last post by:
Hi, I am new to C#, coming from Delphi. In Delphi, I am using a 3rd party string handling library that includes some very useful string functions, in particular I'm interested in BEFORE (return...
5
by: comshiva | last post by:
Hi all, I have converted my existing ASP.NET project from 1.1 to 2.0 and i have found that everything works fine except the linkbutton control in my datagrid which throws an javascript error when...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
4
by: WaterWalk | last post by:
Hello, I'm currently learning string manipulation. I'm curious about what is the favored way for string manipulation in C, expecially when strings contain non-ASCII characters. For example, if...
10
by: micklee74 | last post by:
hi if i have a some lines like this a ) "here is first string" b ) "here is string2" c ) "here is string3" When i specify i only want to print the lines that contains "string" ie the first...
5
by: Niyazi | last post by:
Hi, Does anyone knows any good code for string manipulation similar to RegularExpresion? I might get a value as string in a different format. Example: 20/02/2006 or 20,02,2006 or ...
5
by: ThatVBGuy | last post by:
Hello All, I could really use some help with this problem its driving me nuts. I have a small vb app, the goal of the app is to read an html doc into a variable then go through that variable and...
3
by: crprajan | last post by:
String Manipulation: Given a string like “This is a string”, I want to remove all single characters( alphabets and numerals) like (a, b, 1, 2, .. ) . So the output of the string will be “This is...
3
by: frankeljw | last post by:
I have 2 Java strings 1st String is a series of names, colons, and numbers ie) Name1:13:Name2:4526:Name3:789:Name4:3729:Name5:6:Name6:44 2nd String is a name ie) Name2 I need to get the...
22
by: mann_mathann | last post by:
can anyone tell me a solution: i cannot use the features in standard c++ string classgh i included the string.h file but still its not working.
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.