C 的 fgets 是否可以被哄骗来处理文件中的字符串 *not* ?

标签 c string file fgets

具体来说,代码示例 here效果很好,但只有当字符串存储在文件中时。

有时我需要它来处理生成的字符串(存储在字符串变量中),但我无法说服 fgets 的第三个参数使用字符串变量,因为它是 a pointer to a FILE structure .

或者也许存在可用于字符串的与 fgets 等效的功能?

有什么建议吗?谢谢!

最佳答案

本着拼凑快速答案的精神,这是我刚刚写的“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 );
}

关于C 的 fgets 是否可以被哄骗来处理文件中的字符串 *not* ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2068975/

相关文章:

c - 从 C 中的文本文件中获取每个字符串的第一个字符

python - 文件只写在我的程序末尾

c - 部分初始化 C 结构

c - 如何编写包装函数以便编译器有效地优化它?

java - 如何将字符串设置为等于.txt 文件中的文本

android - 资源问题,(R.drawable.*VARIABLE HERE*);可能的?!安卓

JAVA:包含jar中的文件以及如何访问它们

c - 从 PGM 文件 C 读取矩阵时出现问题

c++ - python和C之间共享配置文件格式?

c - 嵌入式设备的内存分配/释放