2010-07-31 110 views
1

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?我正確地認爲?

回答

1

而不是

if (temp == NULL) 

檢查從與fgets的返回值來代替,如果其爲null,則這將表明故障

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

是,strlen的包括換行符

請注意,如果您位於文件的最後一行,如果您認爲字符串中總是有\ n,那麼在該行結尾處沒有\ n會遇到問題。

另一種方法是像你這樣讀取字符串,但檢查最後一個字符,如果沒有\ n那麼你不應該使用-2偏移量,而是-1。

1

這取決於用於保存文件的操作系統:

  • 適用於Windows,回車符用\ r \ n
  • 爲Linux,他們的\ n
+0

我正在使用Linux Fedora 13.也許我應該這麼說。 – ant2009 2010-07-31 10:18:58

1

難道ü調試並找到Len的具體內容。如果你在c中做這件事,請添加監視並找出你的價值len上顯示的內容。

3

緩衝區中將包含:

"Low, Lisa" 35 F\n\0 

所以-​​2是正確的:strlen的 - 0將是空終止,-1換行符,和-2是字母F.

而且,

if(temp == NULL) { 

temp是一個數組 - 它永遠不能爲NULL。