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];
}
当我觉得它应该返回 16 时,strlen 返回 17。字符串长度包括回车。我觉得我应该做 - 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?我这样想对吗?