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