gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:58:47 24 4
gpt4 key购买 nike

具体来说,代码示例 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com