Avatar of sargent240
sargent240Flag for United States of America asked on

C command line parsing

I am attaching my code and I would like to take the command line argument and put it into buff.  I would like an example on how to get that done.  It seems to me it should not take to many lines of code to do it.  I need to change the line that assigns "Now is the time for all good men" to buff so it will have the info from the command line argument.  Do I just need to change the line in the for statement to assign the command line argument to buff rather than just print it?  Thanks.


    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <termios.h>
    int main(int argc, char *argv[])
    {
    int fd;
    int wd=0;
   
    speed_t baud = B9600; /* baud rate */  

    //unsigned char buff[] = { 0x02, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x23, 0x01, 0x21, 0x03};
    unsigned char buff[] = "Now is the time for all good men\n\r";

    int x;
    for (x=0; x<argc; x++)
      printf("%s\n",argv[x]);
   
    fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY );
    if (fd == -1)
    {     fprintf(stderr, "open_port: Unable to open /dev/ttyS0 - %s\n",
                            strerror(errno));
    }
    else
    {
     
      struct termios settings;
      tcgetattr(fd, &settings);

      cfsetospeed(&settings, baud); /* baud rate */
      settings.c_cflag &= ~PARENB; /* no parity */
      settings.c_cflag &= ~CSTOPB; /* 1 stop bit */
      settings.c_cflag &= ~CSIZE;
      settings.c_cflag |= CS8 | CLOCAL; /* 8 bits */
      settings.c_lflag = ICANON; /* canonical mode */
      settings.c_oflag &= ~OPOST; /* raw output */

      tcsetattr(fd, TCSANOW, &settings); /* apply the settings */
      tcflush(fd, TCOFLUSH);      
     
     
      printf("%d", fd); //i get fd value to be 3
      fcntl(fd, F_SETFL, 0);
      wd=write(fd, buff, strlen(buff));
    }
      printf("%d", wd); //i get wd to be -1, so what is the problem??
      close(fd);
      return 61;
    }
ProgrammingCLinux

Avatar of undefined
Last Comment
sargent240

8/22/2022 - Mon
jkr

I assume you want to put the complete command line (i.e. all arguments instead of the image name itself info 'buff'? that would be like

#include <memory.h> // for 'malloc()'

//...

unsigned char* buff; // a pointer,memory will be allocated dynamically

    size_t sz = 0; // to cont the length of all arguments
    int x;
    for (x=1; x<argc; x++)
      sz += strlen(argv[i]) + 1; // plus a separating space

    buff = (unsigned char*) malloc(sz + 1); // plus the NULL terminator
    *buff = '\0';

    for (x=1; x<argc; x++) {
      strcat(buff,argv[i]);
      if (x < argv - 1) strcat(buff," "); // also add a blank seperator to all but the last arg
    }

// rest of your code

    free(buff); // free the memory again

Open in new window

n2fc

see:  http://einstein.drexel.edu/courses/Comp_Phys/General/C_basics/#command-line

char buff[2000]="";

for (int x=1;  x<argc;  x++)
      strcat(buff, argv[x]);

Open in new window


Note:

1. The loop starts at 1 to SKIP the command itself; start at 0 to include it!

2. The arguments will be concatenated with NO separators.

3. Make sure to allocate an appropriate buffer size, or it may overflow!

ASKER
sargent240

Thank YOU!

This is my present code and when I compile it is get a warning:

al@linux-5t7y:~> gcc serialInC.c
serialInC.c: In function ‘main’:
serialInC.c:32:29: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]                                    
serialInC.c:37:13: warning: comparison between pointer and integer [enabled by default]                                                            


I must have screwed up somewhere along the line
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
n2fc

You will need to post FULL source code to debug the inappropriate use of malloc()...
Probably a typo...

Note that if your command line size is limited, it is unnecessary to use malloc to allocate the buffer!   A buffer slightly larger than the command line is all that is needed!  (See my example above)...
jkr

Sorry, typo on my side, that should have been

    for (x=1; x<argc; x++) {
      strcat(buff,argv[i]);

      // argc, not argv as in my 1st comment
      if (x < argc - 1) strcat(buff," "); // also add a blank seperator to all but the last arg
    }

Open in new window

jkr

BTW, using a static buffer size here is possible - yet then it's always possible to crash your program.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
sargent240

I posted the source and error message a moment ago.  Did you get It?  Thanks
ASKER
sargent240

let me try it this way.  File attached.serialInC.c

al@linux-5t7y:~> gcc serialInC.c
serialInC.c: In function ‘main’:
serialInC.c:32:29: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
serialInC.c:72:7: warning: incompatible implicit declaration of built-in function ‘free’ [enabled by default]
jkr

Nope - as you can see, there's nothing ;o)
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
sargent240

you should have it on this last post.
jkr

Yes, sorry, that was about the same time. Try replacing 'memory.h' with 'stdlib.h'
ASKER
sargent240

the compile error is gone but when I execute it I get a Seg fault.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
sargent240

I execute it with this command:

./a.out This works
ASKER
sargent240

You mentioned in an earlier post that the line;

char buff[2000]="";

should be added some where but as you can see I added:

char buff[256]="";

but that gave me a compiler error about a duplicate declaration.
ASKER CERTIFIED SOLUTION
jkr

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
sargent240

did you try to compile and run the code I posted last?
Your help has saved me hundreds of hours of internet surfing.
fblack61
ASKER
sargent240

I found the problem.  In our original post you used the variable i in two places where it should have been x.  I'll put my code back in again and let you know.
jkr

Well, that I saw also, yet I assumed you had fixed it, since it wouldn't compile otherwise. And no, unfortunately I can't try your original code at the moment.
ASKER
sargent240

Good, Good, Good.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.