C的fgets是否可以使用字符串*而不是来自文件?
发布时间:2020-12-16 03:23:57 所属栏目:百科 来源:网络整理
导读:具体来说,代码示例 here工作得很好,但仅当字符串存储在文件中时才有效. 有时我需要它来处理生成的字符串(存储在字符串变量中),但是我无法说服fgets的第三个参数来处理字符串变量,因为它是a pointer to a FILE structure. 或者也许有一个功能相当于可以在字符
|
具体来说,代码示例
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 = ' '; // 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 = "abcndefghitjklksdnan12345n12345n123456nabcnn";
char buf[5];
while ( sgets( buf,sizeof( buf ),&str ))
printf( "'%s'n",buf );
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
