473,725 Members | 2,039 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

need to parse CL input using strtok()

4 New Member
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 problem with how I've implemented strtok().

I've tried to implement it below, but when I compile it using gcc (no errors/warnings) and try to execute it I get the following output:

com = exit
Segmentation fault (core dumped)

Here is the code snippet:

char command[50]; //Command line input

char com[10]; //Primary command
char file1[20]; //File affected by command (if necessary)
char file2[20]; //2nd file affected by command (if necessary)

char *token; //Used for strtok() function


printf("o-shell>"); //user prompts for o-shell

scanf("%s", command); //command line input from user

//tokenize the command line input using strtok() function
//this produces the command as well as any command line arguments

while(token != NULL)
token = strtok(command, " ");
strcpy(com, token);

printf("com = %s\n", com);

token = strtok(NULL, " ");
strcpy(file1, token);

printf("file1 = %s\n", file1);

token = strtok(NULL, " ");
strcpy(file2, token);

printf("file2 = %s\n", file2);

When I run the program, I get a segmentation fault. Will this code run OK if there are no arguments, just a command? I'm sure the problem is with strtok() either way. thanks!
Jun 30 '07 #1
4 4767
7,435 Recognized Expert Expert
What happens if one of the first calls to strtok returns NULL? Could this be causing the fault?
Jun 30 '07 #2
9,208 Recognized Expert Moderator Expert
When you drop to your while loop the first time, the token has garbage in it.
char *token; //Used for strtok() function
If the garbage is not null, you go inside the loop, corrupt memory and that produces your segmentation fault.

You must always initize pointers before using them.
Jun 30 '07 #3
4 New Member
I redid my code and it partially works right now. I can use strtok to find the first input in the command line, but cannot get the arguments.

The format is <command> <arg1> <arg2>

So far, I've only implemented 'exit' and 'help'. When I run this code, it compiles fine but I get a segmentation fault. I've placed a couple printf to help debug. One of the problems is that the arguments are not detected/counted.

Here is the output:

*************** *************** *************** ******
Welcome to O-Shell! A UNIX shell by O Haqqi

Type 'help' for list of commands, 'exit' to exit
*************** *************** *************** ******

exit was entered
There are 0 arguments
Command is exit
Segmentation fault (core dumped)

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int main(int argc, char *argv[])
char command[50]; //Command line input

//tokens for strtok() funtion
char * com; //Primary command
char * arg1; //First argument of command (usually a file name)
char * arg2; //2nd argument of command (usually a file name)

int args; //Number of arguments entered

printf("******* *************** *************** **************\ n");
printf("Welcome to O-Shell! A UNIX shell by O Haqqi\n\n");
printf("Type 'help' for list of commands, 'exit' to exit\n");
printf("******* *************** *************** **************\ n\n");


printf("o-shell>"); //user prompts for o-shell

scanf("%s", command); //command line input from user

printf("%s was entered\n", command);

com = strtok(command, " \r\n\t");

args = 0;
arg1 = strtok(NULL, " \r\n\t");
if(arg1) args++; //to see if arguments being tracked
arg2 = strtok(NULL, " \r\n\t");
if(arg2) args++; //to see if arguments being tracked

printf("There are %d arguments\n", args);
printf("Command is %s\n", com);
printf("File1 is %s\n", arg1);
printf("File2 is %s\n", arg2);

if ((strcmp(com,"h elp")) ==0 || (strcmp(com,"He lp")) ==0)
printf("\nO-Shell Help Menu:\n");
printf("\nhelp - Print help menu\n");
printf("\nexit - Exit O-Shell\n");
printf("\ntype <file> - Print contents of <file>\n");
printf("\ncopy <file1> <file2> - Copy contents of <file1> to <file2>.");
printf("\n <file2> must be a non-existent file and must be created\n");
printf("\ndelet e <file> - Delete <file>\n\n");

else if ((strcmp(com,"e xit")) ==0 || (strcmp(com,"Ex it")) ==0)
printf("Exiting O-Shell...Goodbye !\n");

printf("Invalid command!!! No operation performed...\n" );


return 0;
Jul 1 '07 #4
9,208 Recognized Expert Moderator Expert
How are these commands being entered???

What does one look like??

Your scanf("%s", command) is going to stop at the first whitespace character. In effect, you will get one word. There will be no \r \n \t in the command becuse they will be eaten by scanf().

Did to mean to use getch() inside a loop??

Please give me an example of usage.
Jul 1 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Johnny Google | last post by:
Here is an example of the type of data from a file I will have: Apple,4322,3435,4653,6543,4652 Banana,6934,5423,6753,6531 Carrot,3454,4534,3434,1111,9120,5453 Cheese,4411,5522,6622,6641 The first position is the info (the product) I want to retreive for the corresponding code. Assuming that the codes are unique for each product and all code data is on one line.
by: Matt | last post by:
Ok, so the exercise is to: Write a program that prints its input one word per line. Does this mean so that when I prest ^Z(ctrl-z) to exit the program if I were to do this: Hey you It would do this:
by: Steven Woody | last post by:
in C, is there any function can be used to decompose tokens from a string? if not, can i find it in CPP? thanks! -- steven woody (id: narke) Celine: Well, who says relationships have to last forever? - Before Sunrise (1995)
by: vvk4 | last post by:
I have an excel spreadsheet that I need to parse. I was thinking of saving this as a CSV file. And then reading the file using C. The actual in EXCEL looks like: a,b a"b a","b a,",b In CSV format looks like: "a,b","a""b","a"",""b","a,"",b" Does anybody have suggestions or have C program based code to parse CSV. Please reply to the message board itself. I do not wish to get spam.
by: Dadio | last post by:
Hi! I have to take some strings from a file and put them in a record... The various strings in the file are written on this way: string1|string2|string3|string4|string5| This is the program that i have just made...what's wrong? #include<stdio.h> #include<conio.h> #include<string.h>
by: federico_bertola | last post by:
I have this code: int RESULT_OF_BLACKLIST = 0; int BlackListMethod( { FILE *blacklist; char String = "I.am.a.dotted.string"; char Word; if ((blacklist = fopen("blacklist.dat", "r")) == NULL) {
by: Richard | last post by:
Which way would you guys recommened to best parse a multiline file which contains two fields seperated by a tab. In this case its the linux/proc/filesystems file a sample of which I have included below: nodev usbfs ext3 nodev fuse vfat ntfs nodev binfmt_misc
by: adolghiu | last post by:
Hi, I have a text file as input which has odd chars like: - // " Bellow is a sample: Jul 6 00:00:13 proxyhost httpd: - "GET http://www.google.com/gwt/i?i=08 9E3394C_C235D1FF_FA6C3045 HTTP/1.1" 200 200 383 78881e-1 N COMPLETE 158 REQ:220:0:130:4:100:0:10:8:30:0:60:0:5:0:200:0 EXE:80:0:125:0:15:0:230:0 MOD :240:0:210:0:90:0:110:0:20:0 RES:40:0:70:30:120:0:260:0 PD:126:0 113 - 1 I read the file line by line and split it...
by: arnuld | last post by:
I searched the c.l.c archives provided by Google as Google Groups with "word input" as the key words and did not come up with anything good. C++ has std::string for taking a word as input from stdin. C takes input in 2 ways: 1) as a character, etchar() 2) as a whole line, fgets()
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,...
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...
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,...
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...
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...
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();...
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...
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.