Search code examples
ccstring

In C, Save one char at a time


I am processing a string in which each word is separated by spaces. The < indicates it is a input redirection, and > indicates it is a output redirection. Ex:

< Hello > World

I want to save the words in different variables (char *in, char *out ) How can I do that? I've looked through the string library and none seems to be able to do the job.

Here's what I have so far concerning this question.

char buff[MAXARGS];
char *str;
char *in;
char *out;

if( strchr(buff, '<') != NULL )
{
  str = strchr(buff, '<');
  str++;
  if( *str == ' ' || *str == '\0' || *str == '\n'  || *str == '\t' )
  {
     fprintf( stdout, "User did not specify file name!\n" );
  }
  else
      in =  str; // This will save Hello > World all together. I don't want that. 
}

Thanks much.


Solution

  • To get you started, here's how you could do it assuming you are allowed to modify buff, and assuming a simple case (at most one < and at most one >).

    First, get the position of the < and >

    in  = strchr(buff, '<');
    out = strchr(buff, '>');
    

    Then you artificially split the string:

    if (in) {
      *in = 0;
      in++;
    }
    if (out) {
      *out = 0;
      out++;
    }
    

    At this point, buff points to a C-terminated string that has no < or >. in is either null, or points to a string that follows < and contains no >. Same for out.

    Then you need to "strip" all these strings (remove whitespace), and check that after that they still contain meaningful data.

    You'll need a whole lot more logic to get all the cases right, including rejecting invalid input.