473,729 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(lin e, 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:3 0001
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
14 1763
On 5 Oct 2006 04:10:04 -0700, "Ancient_Hacker " <gr**@comcast.n et>
wrote:
>
aq***@inbox.co m 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(li ne, SIZE_OF_LINE + 1, fp) != NULL)

similarly: while(fgets(lin e, 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.n etwrites:
Richard Heathfield wrote:
>Ancient_Hack er 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_Keit h) 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
4315
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 substring before a pattern), AFTER (return substring after a pattern), and BETWEEN (return substring between 2 patterns). My questions are: 1. Can any tell me how I can implement such functionality in C#? 2. Is it possible to add/include function...
5
2601
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 clicked. I thought the control might be the problem, so i deleted the old control and binded the new linkbutton control but am still getting the same error. Am using visual studio 2005. Source code inside my grid:...
2
4453
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 */ #include <time.h>
4
3488
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 substrings need be replaced, or one character needs be changed, what shall I do? Is it better to convert strings to UCS-32 before manipulation? But on Windows, wchar_t is 16 bits which isn't enough for characters which can't be simply encoded...
10
1769
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 line and not the others. If i use re module, how to compile the expression to do this? I tried the re module and using simple
5
7485
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 20.02.2006 etc... And I want to replace the /,.etc character with - (as 20-02-2006)
5
3534
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 find and replace some tags. I have 3 functions. 1 to open the doc, the 2nd to find and replace the tags the 3rd to save the info. the code is pasted below : Public Function ReadFileContents(FileFullPath As String) As _ String On Error GoTo...
3
1562
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 string” This is very urgent. Please help
3
3562
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 number associated with that name.
22
2609
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
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.