2010-07-31 49 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。