可以哄骗C的fgets使用字符串*而不是文件吗?

Mon*_*urd 8 c string file fgets

具体来说,此处的代码示例效果很好,但仅当字符串存储在文件中时才有效.

有时我需要它来处理生成的字符串(存储在字符串变量中),但是我无法说服fgets的第三个参数来处理字符串变量,因为它是指向FILE结构的指针.

或者也许有一个功能相当于可以在字符串上使用的fgets?

有什么建议?谢谢!

Mar*_*ins 9

本着劈砍快速答案的精神,这里是我刚写的"sgets".它试图模拟fgets但使用字符串输入.

编辑修复了Monte指出的错误(谢谢).疯狂地输入一个实用程序,同时相信至少有15个具有完全相同想法的其他人疯狂地做同样的事情并不会导致经过良好测试的代码.不好意思 原始版本在后续调用中包含换行符.

char *sgets( char * str, int num, char **input )
{
    char *next = *input;
    int  numread = 0;

    while ( numread + 1 < num && *next ) {
        int isnewline = ( *next == '\n' );
        *str++ = *next++;
        numread++;
        // newline terminates the line but is included
        if ( isnewline )
            break;
    }

    if ( numread == 0 )
        return NULL;  // "eof"

    // must have hit the null terminator or end of line
    *str = '\0';  // null terminate this tring
    // set up input for next call
    *input = next;
    return str;
}


int main( int argc, char* argv[] )
{
    // quick and dirty test
    char *str = "abc\ndefghitjklksd\na\n12345\n12345\n123456\nabc\n\n";
    char buf[5];

    while ( sgets( buf, sizeof( buf ), &str ))
        printf( "'%s'\n", buf );
}
Run Code Online (Sandbox Code Playgroud)


R S*_*hko 5

标准 C 库不提供该功能。

但 AT&T 的安全/快速 I/O 库确实支持内存流,并且还提供包装器代码以使用 FILE API 及其扩展。最后一次更新是 2005 年 2 月,所以要么他们最终解决了所有错误,要么因为卢克·威尔逊 (Luke Wilson) 已经在工资单上了,他们再也无力维护它了:-(

该软件包可以在这里下载