fgets()总是空终止它返回的字符串吗? [英] Does fgets() always null-terminate the string it returns?

查看:217
本文介绍了fgets()总是空终止它返回的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是安全的吗? fgets 是否以null终止缓冲区,或者是在调用 fgets 之前和之前设置第20个字节为空我打电话给干净

  //换行
(* data)
{
while(* data)
{
if(* data =='\ n'|| * data =='\ r')* data ='\0';
data ++;



//为此,假设文件包含1行不超过19字节
//缓冲区在其他地方被释放
char * load_latest_info(char * file)
{
FILE * f;
char * buffer =(char *)malloc(20);
if(f = fopen(file,r))
if(fgets(buffer,20,f))
{
clean(buffer);
返回缓冲区;
}
free(buffer);
返回NULL;


解决方案

fgets()总是正确的空终止缓冲区。从手册页
$ b


()函数最多只读取一个小于 n 从给定的流中存储并存储在字符串 s 中。当
换行符被发现时,读取停止,文件结束或错误。换行符,如果有的话,保留。如果读取了任何字符并且没​​有错误,则在字符串结尾附加一个 \ 0 字符



Is this safe to do? Does fgets terminate the buffer with null or should I be setting the 20th byte to null after the call to fgets and before I call clean?

// strip new lines
void clean(char *data)
{
    while (*data)
    {
        if (*data == '\n' || *data == '\r') *data = '\0';
        data++;
    }
}

// for this, assume that the file contains 1 line no longer than 19 bytes
// buffer is freed elsewhere
char *load_latest_info(char *file)
{
    FILE *f;
    char *buffer = (char*) malloc(20);
    if (f = fopen(file, "r"))
        if (fgets(buffer, 20, f))
        {
            clean(buffer);
            return buffer;
        }
    free(buffer);
    return NULL;
}

解决方案

Yes fgets() always properly null-terminates the buffer. From the man page:

The fgets() function reads at most one less than the number of characters specified by n from the given stream and stores them in the string s. Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a '\0' character is appended to end the string.

这篇关于fgets()总是空终止它返回的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆