LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   simple c question (getline) (https://www.linuxquestions.org/questions/programming-9/simple-c-question-getline-215874/)

aaa 08-10-2004 01:39 PM

simple c question (getline)
 
I have a line-oriented file-format, and use get line to retrieve the data. However, the (string) data can not have the newline character. I am trying to write a function that doesn't return a string with the newline, but I'm having trouble:

Code:

char * getlineNoEndl(FILE *file)
{
  char *str = NULL;
  int strsize = 0;

  getline(&str, &strsize, file);

  if (strsize >= 2)
  {
    /* shrink string */
    str = realloc(str, (--strsize) * sizeof(char));
    str[strsize - 1] = '\0';
  }
  else
  {
    free(str);
    str = malloc(sizeof(char));
    *str = '\0';
  }
 
  return str;
}

The function currently appears to still return a string with a newline in it.

itsme86 08-10-2004 02:51 PM

Different operating systems use different End Of Line markers. An easy way would be to do something like this:
Code:

int i;

for(i = 0;i < strsize;++i)
  if(!isprint(str[i]))
    break;
str[i] = '\0';

The \r or \n at the end of the line will cause isprint() to return 0 and break the loop. Then you can null-terminate the string at that point. If you're concerned about realloc()'ing the string you can use strsize-i to figure out how much to shrink str by.

aluser 08-10-2004 05:53 PM

I think the reason the original wasn't working is that the second argument to getline gets filled in with the amount of space *allocated* to the pointer in the first argument, not the actual number of characters read. You should be using the return value of getline to find the position of the newline instead.

I *believe* that fopen without the "b" modifier to the mode will convert whatever the system's newline character is to \n, so you don't have to worry about different newlines. I'm not sure if I'm remembering right though.

aaa 08-18-2004 03:02 PM

Got it working with this:
Code:

char * getlineNoEndl(FILE *file)
{
  char *str = NULL;
  int strsize = 0;

  strsize = getline(&str, &strsize, file);
 
  if (strsize < 0)
    return NULL;
 
  if (strsize >= 1)
  {
    /* shrink string */
    str = realloc(str, (strsize) * sizeof(char));
    str[strsize - 1] = '\0';
  }
  else
  {
    free(str);
    str = malloc(sizeof(char));
    *str = '\0';
  }
  return str;
}

However, I have encountered another problem


All times are GMT -5. The time now is 02:37 AM.