tags:

views:

64

answers:

4

Hello,

gcc 4.4.4 c89

I am using the following code to read in file using fgets. I just want to get the gender which could be either M or F.

However, as the gender is always the last character in the string. I thought I could get the character by using strlen. However, for some reason I have to get the strlen and minus 2. I know that the strlen doesn't include the nul. However, it will include the carriage return.

The exact line of text I am reading in is this:

"Low, Lisa" 35 F

My code:

int read_char(FILE *fp)
{
#define STRING_SIZE 30
    char temp[STRING_SIZE] = {0};
    int len = 0;

    fgets(temp, STRING_SIZE, fp);

    if(temp == NULL) {
        fprintf(stderr, "Text file corrupted\n");
        return FALSE;
    }

    len = strlen(temp);
    return temp[len - 2];
}

The strlen returns 17 when I feel it should return 16. String length including the carriage return. I feel I should be doing - 1 instead of - 2.

Any suggestions if you understand my question.

Thanks,

EDIT:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to  by  s.   Reading  stops
       after  an  EOF  or  a  newline.  If a newline is read, it is stored into the buffer.  A '\0' is stored after the last character in the
       buffer

So the buffer will contain:

"Low, Lisa" 35 F\0\r

Which will return 17 from strlen if it is including the \r? Am I correct in thinking that?

+2  A: 

It depends on the operating system used to save the files :

  • for Windows, carriage returns are \r\n
  • for Linux, they are \n
wok
I am using Linux Fedora 13. Maybe I should have said that.
robUK
+1  A: 

Did u debug and find what exactly coming at Len. If u are doing it in c add watch and find out the what is displaying at your value len.

Dorababu
+3  A: 

The buffer will contain:

"Low, Lisa" 35 F\n\0

so -2 is correct: strlen - 0 would be the null terminator, -1 the newline, and -2 is the letter F.

Also,

if(temp == NULL) {

temp is an array - it can never be NULL.

anon
+1  A: 

Instead of

if (temp == NULL) 

check the return value from fgets instead, if its null then that would indicate failure

if ( fgets(temp, STRING_SIZE, fp) == NULL )

yes, strlen includes the newline

note that if you are on the last line of the file and there is no \n at the end of that line you make encounter a problem if you assume there is always \n in the string.

an alternative way would be to read the string as you do but check the last char, if there is no \n then you shouldn't use -2 offset but -1 instead.

Anders K.