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];
}

当我觉得它应该返回 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?我这样想对吗?

4

4 回答 4

3

缓冲区将包含:

"Low, Lisa" 35 F\n\0

所以 -2 是正确的:strlen - 0 是空终止符,-1 是换行符,-2 是字母 F。

还,

if(temp == NULL) {

temp 是一个数组 - 它永远不能为 NULL。

于 2010-07-31T10:35:05.020 回答
1

这取决于用于保存文件的操作系统:

  • 对于 Windows,回车是 \r\n
  • 对于 Linux,它们是 \n
于 2010-07-31T10:17:12.850 回答
1

你有没有调试并找到 Len 到底发生了什么。如果您在 c 中执行此操作,请添加手表并找出您的价值 len 显示的内容。

于 2010-07-31T10:20:15.447 回答
1

代替

if (temp == NULL) 

检查 fgets 的返回值,如果它为空,则表示失败

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

是的,strlen 包括换行符

请注意,如果您在文件的最后一行并且在该行的末尾没有 \n 如果您假设字符串中始终存在 \n ,那么您会遇到问题。

另一种方法是像你一样读取字符串但检查最后一个字符,如果没有 \n 那么你不应该使用 -2 偏移量而是 -1 。

于 2010-07-31T10:57:20.227 回答