Question

Possible Duplicate:
memcpy and malloc to print out a string

I need to find the number of characters in a line of a text file after a '=' sign until the end of the line or the '#' symbol. I then need to work backwards till I reach the first non blankspace and use memcpy to print out the string.

Example: if the line said: myprop=this is a sentence #value, I need it to print out :"this is a sentence". here is the code after I open the file and malloc it.

while(fgets(buffer, 1024, fp) != NULL)
{
 if((strstr(buffer, propkey)) != NULL)
 {
  for (

   //need help here


  memcpy(value, buffer + 7, 7);  //the 7 represents the # of characters till the equal sign
  printf("\nvalue is '%s'\n", value);
  }
 } 
Was it helpful?

Solution

You find the '=' via strchr().

Loop from there until you hit either '\0' or '#'. Count the loops. Inside the loop, check for first non-blankspace (isspace()), and keep in mind (i.e., a variable) where you found it.

After the loop, you have all the information you need: Copy (starting from remembered position of first non-blank) a number of bytes equal ( number of loops - position of first non-blank ).

That being said, once you're out of tutorial / C in 21 days country, you should really use ready-made libraries for stuff like this..

OTHER TIPS

You can get it with sscanf like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char buf[] = "myprop= this is a sentence #comment";
char value[100];

void get_value(char *buf, char *value)
{
    int len;
    sscanf(buf,"%*[^=]= %[^#]",value);
    len = strlen(value);
    while((--len) && value[len]==' ')
        value[len] = '\0';
}

int main()
{
    get_value(buf, value);
    printf ("The value is __%s__\n",value);
}

sscanf(buf,"%*[^=]= %[^#]",value);: This will get the string starting from = till the # and the space characters in the beggining will not capted but the space characters at the end will be capted

And to remove the space characters at the end of the capted string I used the following code:

len = strlen(value);
while((--len) && value[len]==' ')
    value[len] = '\0';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top