gcc 4.4.4 c89在文件中读取并获取字符串长度
我正在使用以下代码在使用fgets读取文件中。我只想得到可能是M或F的性别。
但是,性别总是字符串中的最后一个字符。我以为我可以通过使用strlen来获得角色。但是,由于某种原因,我必须得到strlen和-2。我知道strlen不包括nul。但是,它将包含回车。
文字,我读的确切路线是这样的:
"Low, Lisa" 35 F
我的代码:
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];
}
strlen的返回17时,我觉得它应该返回16,包括车厢长度的字符串返回。我觉得我应该做的 - 1而不是 - 2.
如果你明白我的问题,任何建议。
感谢,
编辑:
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
因此,缓冲区将包含:
"Low, Lisa" 35 F\0\r
如果包括\ r将从strlen的返回17?我正确地认为?
我正在使用Linux Fedora 13.也许我应该这么说。 – ant2009 2010-07-31 10:18:58