我有一个名为 buf 的 C 数组。这是它的定义:
char buf[1024];
现在,我当前的代码取自stdin
并用于fgets()
设置该数组,但是我希望使用代码来设置它。现在设置 buf 的行如下所示:
fgets(buf, 1024, stdin);
基本上,我想用“我的字符串”替换标准输入。最好的方法是什么?
snprintf 只是 C99 而不是 C89,sprintf_s/strcpy_s 只是 MSVC,不是 C89,不是 C99。
char *mystr="come from stdin or file or ...";
char buf[1024];
...
memset(buf,0,sizeof buf);
strncpy(buf,mystr,(sizeof buf)-1);
或非数组:
#define BUFLEN 512
char *mystr="come from stdin or file or ...";
char *buf;
...
char *buf=calloc(1,BUFLEN);
strncpy(buf,mystr,BUFLEN-1);
它适用于所有 ANSI C 环境。
strcpy(buf, "My String");
Microsoft 的编译器还包括一个函数 strcpy_s,它是 strcpy 的“安全”版本。它确保您不会超支buf
。在这种特殊情况下,这可能不是问题,但您应该知道。但是,请注意,它不适用于任何其他编译器,因此它不能用于需要可移植的地方。
strcpy_s(buf, sizeof(buf), "My String");
有很多变体,有些已经提出,有些还没有:
...
char input[] = "My String";
strcpy(buf, input);
strncpy(buf, input, sizeof(buf));
sscanf(input, "%s", buf);
sprintf(buf, "%s", input);
memcpy(buf, input, strlen(input));
...
他们中的大多数人不确定/不安全。究竟应该采取什么取决于你真正想在你的代码中做什么。
问候
rbo
详细但安全:
int copy_size = sizeof( buf ) - 1 < strlen( MyString ) ? sizeof( buf ) - 1 : strlen( MyString );
memset( buf, 0, copy_size + 1 );
memcpy( buf, MyString, copy_size );