从 C 命令行读取
我有一个在命令行中运行的程序(C 语言),我希望它接受来自用户的任意长度的字符串。如果我用 C++ 编程,我可能会使用字符串库中的 getline() 函数,但我似乎找不到 C 等效函数。我是否只需要读取 X 长度的块中的字符,如果字符串超过 X 长度,则创建一个新的更大的块并将数据复制到新块?
I have a program (in C) that runs in the command line, and I am looking to have it accept strings of arbitrary length from users. If I were programming in C++, I would probably use the getline() function in the string library, but I can't seem to find a C equivalent. Do I just need to read characters in blocks of X length, and if the string goes over X length, make a new bigger block and copy data over to the new block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将
fgets
与sscanf
结合使用。请注意,
getline
现在已出现在当前的 POSIX:2008 标准中。http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
You can use
fgets
withsscanf
.Note that
getline
is now present in the current POSIX:2008 standard.http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
使用readline库 http://cnswww.cns.cwru.edu/php /chet/readline/rltop.html(如果您不喜欢该许可证,还有一个 BSD 等效许可证)。
从那里,您可以使用函数
readline()
,它将返回用户键入的行的char *
(请确保调用free ()
完成后就可以了,否则会出现内存泄漏)。您甚至可以设置一些选项,以便您的用户可以按向上箭头来获取他们的上一行(就像几乎所有其他终端一样)。Use the readline library http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html (if you don't like the license there is also a BSD equivalent).
From there, you get to use the function
readline()
, which will return to you achar *
of the line the user typed (make sure to callfree()
on it when you're done or you will have a memory leak). There is even options you can set so that your users can press the up arrow to get their previous line (like in almost every other terminal).您可以使用
realloc()
来增加输入缓冲区。无需复制数据过来;它会为你做到这一点。一个常见的模式是:You can use
realloc()
to grow your input buffer. There is no need to copy the data over; it does that for you. A common pattern is: