具体来说,代码示例
here工作得很好,但仅当字符串存储在文件中时才有效.
有时我需要它来处理生成的字符串(存储在字符串变量中),但是我无法说服fgets的第三个参数来处理字符串变量,因为它是a pointer to a FILE structure.
有什么建议?谢谢!
解决方法
本着快速回答黑客的精神,这里是我刚写的“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 ); }
原文地址:https://www.jb51.cc/c/111570.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。