473,761 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to parse a string like C program parse the command line string?

I want to parse a string like C program parse the command line into
argc & argv[][].
I hope don't use the array the allocate a fix memory first, and don't
use the memory allocate function like malloc.
who can give me some ideas?
The following is my program, but it has some problem. I hope someone
would correct it.
////////////////////////////
//Test_ConvertArg .c
////////////////////////////
#include <stdio.h>
#include <string.h>

int ConvertArg(char * Str, char* Argv[])
{
int Argc; // Count the argument).
int Count = 0;
int i = 0;
char* StrPtr;
char* TmpStrPtr;
StrPtr = Str;

for(; *StrPtr == ' ';) // ignore the whitespace before the
command!
{
++StrPtr;
}

TmpStrPtr = StrPtr;

for (Argc = 0; (*StrPtr) != '\n'; StrPtr++, Count++)
{

if(*StrPtr == ' ')
{
// if exist multi whitespace together,
//argc just count once,and don't continually change argv!
if( *(StrPtr+1) == ' ')
{
Count--;
continue;
}
}

Count--;
// the following setences have problems.
memcpy(Argv[Argc],TmpStrPtr,Coun t);

#if 0
for(i=0; i <= Count; i++)
{
Argv[Argc][i] = *TmpStrPtr;
TmpStrPtr++;
}
#endif
TmpStrPtr = StrPtr;
i = 0;
Argc++;
}
}

int main(int argc, char* argv[])
{
char** argv1;
char* str = "";

char** str1 = "test";
char* str2 = " ";
memcpy(str2, str1[0], 4);
printf("%s\n", str2);
// test ConvertStr()
str = " a asdf ";
argv1 = "";
printf("argc = %d, argv0 = \n",ConvertArg( str, argv1));
str = " a asdf";
printf("argc = %d, argv0 = %s ,argv1 = %s\n",ConvertAr g(str, argv1),
argv1[0], argv1[1]);
str = " asdf asdf";
printf("argc = %d, argv0 = %s ,argv1 = %s\n",ConvertAr g(str, argv1),
argv1[0], argv1[1]);
str = " asdf asdf";
printf("argc = %d, argv0 = %s ,argv1 = %s, argv2 =
%s\n",ConvertAr g(str, argv1), argv1[0], argv1[1], argv1[3]);
return 1;
}

Nov 14 '05 #1
19 20585

<li************ @163.com> schreef in bericht
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I want to parse a string like C program parse the command line into
argc & argv[][].
I hope don't use the array the allocate a fix memory first, and don't
use the memory allocate function like malloc.
who can give me some ideas?
The following is my program, but it has some problem. I hope someone
would correct it.
////////////////////////////
//Test_ConvertArg .c
////////////////////////////
#include <stdio.h>
#include <string.h>

int ConvertArg(char * Str, char* Argv[])
{
int Argc; // Count the argument).
int Count = 0;
int i = 0;
char* StrPtr;
char* TmpStrPtr;
StrPtr = Str;

for(; *StrPtr == ' ';) // ignore the whitespace before the
command!
{
++StrPtr;
}

TmpStrPtr = StrPtr;

for (Argc = 0; (*StrPtr) != '\n'; StrPtr++, Count++)
{

if(*StrPtr == ' ')
{
// if exist multi whitespace together,
//argc just count once,and don't continually change argv!
if( *(StrPtr+1) == ' ')
{
Count--;
continue;
}
}

Count--;
// the following setences have problems.
memcpy(Argv[Argc],TmpStrPtr,Coun t);

#if 0
for(i=0; i <= Count; i++)
{
Argv[Argc][i] = *TmpStrPtr;
TmpStrPtr++;
}
#endif
TmpStrPtr = StrPtr;
i = 0;
Argc++;
}
}

int main(int argc, char* argv[])
{
char** argv1;
char* str = "";

char** str1 = "test";
char* str2 = " ";
memcpy(str2, str1[0], 4);
printf("%s\n", str2);
// test ConvertStr()
str = " a asdf ";
argv1 = "";
printf("argc = %d, argv0 = \n",ConvertArg( str, argv1));
str = " a asdf";
printf("argc = %d, argv0 = %s ,argv1 = %s\n",ConvertAr g(str, argv1),
argv1[0], argv1[1]);
str = " asdf asdf";
printf("argc = %d, argv0 = %s ,argv1 = %s\n",ConvertAr g(str, argv1),
argv1[0], argv1[1]);
str = " asdf asdf";
printf("argc = %d, argv0 = %s ,argv1 = %s, argv2 =
%s\n",ConvertAr g(str, argv1), argv1[0], argv1[1], argv1[3]);
return 1;
}


use the getopt function

Johan
Nov 14 '05 #2
but my program is not want to run under the systemV Unix or something
like it.
That is not getopt system call

Nov 14 '05 #3
I rewrite the Convert function like following:
//////////////////////
///////////////////////////////////////////////////////////////////////////////
///////
//PURPOSE : This function converts the Str into [int argc] & [char*
argv[]],
// which are the same as the argument of the C main function.
//
//ARGUMENT : Str contains the command , switch and archive file.
//RETURN : the number in of the argument.
//INFO : 1.skip leading white space and table space!
// 2.if occur the '\0' break;
// 3.Put the remain string into the Argv[Argc], be remember Argv[]
// is a string Pointer. if you file '\0' in string it means that
// you fill the Argv[][].
// 4.check the ' ' '\t' '\n'
// 5.fill the string by '\n'
// 6.change the string pointer to the next argument.
//TestStatus: UNDO
///////////////////////////////////////////////////////////////////////////////
///////
int ConvertArg(char * Str)
{
int Argc; // Count the argument).
char* Argv[MAXARGC]; // to hold the parse result.
char *StrPtr, *CurrentPtr;
StrPtr = Str;

for(Argc = 0;Argc < MAXARGC;Argc++) // init the Argv.
{
Argv[Argc] = NULLCHAR;
}
for(Argc = 0;Argc < MAXARGC && (*StrPtr) != '\0';)
{
// Skip leading white space and table space!
while(*StrPtr == ' ' || *StrPtr == '\t')
{
StrPtr++;
}

// When that is only space in the string this instance will happen!
if((*StrPtr) == '\0') // break if occur the char '\0'
{
break;
}

Argv[Argc++] = StrPtr; // Beginning of token.

// Find space or tab. If not present then we've already found the
last token.
for (CurrentPtr = StrPtr; *CurrentPtr; CurrentPtr++)
{
if (*CurrentPtr == ' ' || *CurrentPtr == '\t')
{
break;
}
}

if (*CurrentPtr != '\0')
{
*CurrentPtr++ = '\0';
}
StrPtr = CurrentPtr;
}

// empty command line
if (Argc < 1)
{
Argc = 1;
Argv[0] = "";
}

return Argc;
}

Nov 14 '05 #4
On 11 Mar 2005 22:00:35 -0800, in comp.lang.c , li************@ 163.com wrote:
but my program is not want to run under the systemV Unix or something
like it.
That is not getopt system call


the source for getopt() is available in the public domain. Try the gnu archives.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >
Nov 14 '05 #5
Mark McIntyre wrote:
li************@ 163.com wrote:
but my program is not want to run under the systemV Unix or
something like it.That is not getopt system call


the source for getopt() is available in the public domain. Try the
gnu archives.


You mean "The source for some version of something sometimes known
as getopt is ...,". There is no standard for this. For example,
the following is viable:

char *getopt(void) {return "opt";}

illustrating why the content of this group is constrained. :-)

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #6
CBFalconer wrote:
Mark McIntyre wrote:
li************@ 163.com wrote:
but my program is not want to run under the systemV Unix or
something like it.That is not getopt system call


the source for getopt() is available in the public domain. Try the
gnu archives.


You mean "The source for some version of something sometimes known
as getopt is ...,". There is no standard for this. For example,
the following is viable:

char *getopt(void) {return "opt";}


Almost certainly not. getopt is covered by POSIX.
Daniel Vallstrom

Nov 14 '05 #7
Mac
On Sat, 12 Mar 2005 11:16:06 +0000, Mark McIntyre wrote:
On 11 Mar 2005 22:00:35 -0800, in comp.lang.c , li************@ 163.com wrote:
but my program is not want to run under the systemV Unix or something
like it.
That is not getopt system call


the source for getopt() is available in the public domain. Try the gnu archives.


I would be very surprised if GNU put any of their stuff into the public
domain. AFAIK, GNU (or the FSF) maintains copyright ownership of all their
software and licenses it according to the GPL or LGPL.

--Mac

Nov 14 '05 #8
On Sat, 12 Mar 2005 16:10:02 GMT, in comp.lang.c , CBFalconer
<cb********@yah oo.com> wrote:
Mark McIntyre wrote:
li************@ 163.com wrote:
but my program is not want to run under the systemV Unix or
something like it.That is not getopt system call
the source for getopt() is available in the public domain. Try the
gnu archives.


You mean "The source for some version


indeed. I was merely indicating that
a) the wheel doesn't need reinvented
b) getopt is not restricted to SysV.
illustrating why the content of this group is constrained. :-)


Well, that was rather why I redirected out of it.... :-)
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #9
On Sat, 12 Mar 2005 17:13:31 GMT, in comp.lang.c , Mac <fo*@bar.net> wrote:
On Sat, 12 Mar 2005 11:16:06 +0000, Mark McIntyre wrote:
On 11 Mar 2005 22:00:35 -0800, in comp.lang.c , li************@ 163.com wrote:
but my program is not want to run under the systemV Unix or something
like it.
That is not getopt system call


the source for getopt() is available in the public domain. Try the gnu archives.


I would be very surprised if GNU put any of their stuff into the public
domain. AFAIK, GNU (or the FSF) maintains copyright ownership of all their
software and licenses it according to the GPL or LGPL.


A rose.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #10

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

Similar topics

4
2192
by: Andrew E | last post by:
Hi all I've written a python program that adds orders into our order routing simulation system. It works well, and has a syntax along these lines: ./neworder --instrument NOKIA --size 23 --price MARKET --repeats 20 etc However, I'd like to add a mode that will handle, say:
22
872
by: Ram Laxman | last post by:
Hi all, I have a text file which have data in CSV format. "empno","phonenumber","wardnumber" 12345,2234353,1000202 12326,2243653,1000098 Iam a beginner of C/C++ programming. I don't know how to tokenize the comma separated values.I used strtok function reading line by line using fgets.but it gives some weird behavior.It doesnot stripout the "" fully.Could any body have sample code for the same so that it will be helfful for my...
1
2218
by: slonocode | last post by:
I have created a filter in Eudora email program that will notify a program when the criteria is met. For instance if the filter criteria is met it will send the following command: C:\MyProgam.exe "C:\MyFile.txt" I have been able to process the command line by writing a small sub main in a module and that works fine. But I need for their to be only 1 instance of the program. As it is now it opens a new instance of MyProgram.exe...
14
1844
by: Erik | last post by:
Hi, i'm trying to do this : #include <stdlib.h> #include <stdio.h> #define FILE "/tmp/myfile" #define USERS_LIST "/tmp/userslist" int main() { //open file
4
5895
by: sturnfie | last post by:
Hey all, I recently came across the xml.sax libraries and am trying to use them. I am currently making a string variable, and am attempting to pass it into a parser instance as follows: def parseMessage(self, message): #create a XML parser parser = make_parser() #create an instance of our handler class #generic, prints out to screen on all events
1
64189
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C programming. FYI Although I have called this article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts, disregarding the syntax that stream contains. Parsing is actually including the syntax in order to make...
4
4769
by: ohaqqi | last post by:
Hi everybody. I haven't programmed anything in about 8 years, I've read up a little bit on C and need to write a shell in C. I want to use strtok() to take an input from a user and parse it into the command and its arguments. for example: copy <file1> <file2> will copy file 2 to file 1, del <file1> will delete a file, etc. The exit command is all I've implemented right now, but even that produces an error when executed...I'm sure I've got a...
2
3227
by: Lawrence Krubner | last post by:
Imagine a template system that works by getting a file, as a string, and then putting it through eval(), something like this: $formAsString = $controller->command("readFileAndReturnString", $formName); // 06-22-07 - the next commands try to import all the functions that the
9
2210
by: Krumble Bunk | last post by:
Hi all, I am trying my hands at writing a shell for unix. A very rubbish shell, but nonetheless, I come to a point where I am confused. I would like to have something like shellstop xyz whereupon the command "stop" will take the argument "xyz" and perform
0
9377
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
10136
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...
1
9925
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
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8814
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...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
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
5266
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
3913
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.