捕获来自在C命令行可变长度的字符串 [英] Capturing a variable length string from the command-line in C
问题描述
我到处找一个回答我的问题,但我还没有找到一个坚实的回答我的问题。
I've looked everywhere for an answer to my question, but I have yet to find a solid answer to my problem.
我目前在用C写程序,专门针对UNIX命令行的过程中(我使用Linux作为我的开发环境,但我想这个计划,以尽可能便携式)。现在,我有一个提示用户输入一个基本的shell。然后用户将在一个命令输入,并且该命令将被相应地进行处理。这里是code,我到目前为止有:
I'm currently in the process of writing a program in C, specifically targeting the UNIX command line (I'm using Linux as my development environment, but I'd like for this program to be as portable as possible). Right now, I have a basic shell that prompts for user input. The user will then enter in a command, and that command will be processed accordingly. Here is the code that I have so far:
/* Main.c */
int main(int argc, char **argv)
{
while (TRUE)
{
display_prompt();
get_command();
}
return 0;
}
/* Main.h */
void get_command()
{
/*
* Reads in a command from the user, outputting the correct response
*/
int buffer_size = 20;
char *command = (char*) malloc(sizeof(char) * buffer_size);
if (command == NULL)
{
return_error("Error allocating memory");
}
fgets(command, buffer_size, stdin);
if (command[strlen(command) - 1] == '\n')
{
puts("It's inside the buffer.");
}
else
{
puts("It's not inside the buffer.");
}
free(command);
}
我最初的想法是要检查 \\ n
字符,看看它是否适合在 BUFFER_SIZE
,和如果没有的realloc()
数据扩大分配的内存。
My initial thought was to check for the \n
character and see if it fit within the buffer_size
, and if it didn't realloc()
the data to expand the allocated memory.
然而,当我的realloc()
我的字符串,我将如何去从标准输入
将剩余的数据到命令
?
However, after I realloc()
my string, how would I go about adding the remaining data from stdin
into command
?
推荐答案
使用函数getline(3)如果你真的需要。这是POSIX.1-2008。而且要知道,长度不限行是DOS攻击(OOM)一个简单的攻击向量。所以考虑一个合理的线路长度的限制,并使用与fgets(3)。
Use getline(3) if you really need. It's POSIX.1-2008. And be aware that unlimited length lines are an easy attack vector for DOS-attacks (OOM). So consider making up a reasonable line length limit, and using fgets(3).
这篇关于捕获来自在C命令行可变长度的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!