【问题标题】:reading in a file and getting the string length读取文件并获取字符串长度
【发布时间】:2011-03-23 14:27:49
【问题描述】:

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?我这样想对吗?

【问题讨论】:

    标签: c fgets


    【解决方案1】:

    缓冲区将包含:

    "Low, Lisa" 35 F\n\0
    

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

    还有,

    if(temp == NULL) {
    

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

    【讨论】:

      【解决方案2】:

      代替

      if (temp == NULL) 
      

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

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

      是的,strlen 包含换行符

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

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

      【讨论】:

        【解决方案3】:

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

        • 对于 Windows,回车是 \r\n
        • 对于 Linux,它们是\n

        【讨论】:

        • 我使用的是 Linux Fedora 13。也许我应该这么说。
        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-28
          • 2022-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-12
          • 2013-01-23
          相关资源
          最近更新 更多