C 在使用旧内容之前正在写入缓冲区
是否可以使用memset()初始化缓冲区,然后使用不同的调用向其添加特定数据 例如:C 在使用旧内容之前正在写入缓冲区,c,C,是否可以使用memset()初始化缓冲区,然后使用不同的调用向其添加特定数据 例如: DIR *dirp; struct dirent *dp; struct dirent *buf; dirp = opendir("/dev"); if( dirp ) { buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + NAM
DIR *dirp;
struct dirent *dp;
struct dirent *buf;
dirp = opendir("/dev");
if( dirp ) {
buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + NAME_MAX + 1);
if (buf == NULL) {
closedir( dirp );
return = ENOMEM;
}
while( readdir_r(dirp, buf, &dirp) == 0 && dirp ) {
if( strncmp( dp->d_name, "video", 5 ) == 0 ) {
char vidpath[21];
memset( vidpath, 0x0, sizeof( vidpath ) );
snprintf( vidpath, 20, "/dev/%s", dp->d_name );
// Now do an operation that prints the buffer...
}
}
free ( buf );
closedir( dirp );
}
“注意”
memset
将内存初始化为给定的值,因此确保没有不必要的副作用是绝对有效的良好做法。因为您无论如何都在使用snprintf,所以它不是严格必要的,因为您要传递的是size-1,所以memset在循环中不应该是必需的
不过,对于snprintf,也应该使用sizeof(vidpath)
snprintf( vidpath, sizeof(vidpath), "/dev/%s", dp->d_name );
首先,请注意:
char vidpath[21];
memset( vidpath, 0x0, sizeof( vidpath ) );
可以写为:
char vidpath[21] = {0};
但是,当然,按您的方式调用memset
是有效的
现在,当您调用snprintf
时,没有必要先初始化缓冲区
也不是:
snprintf( vidpath, 20, "/dev/%s", dp->d_name );
你可以写
snprintf( vidpath, 21, "/dev/%s", dp->d_name );
或者更好
snprintf( vidpath, sizeof vidpath, "/dev/%s", dp->d_name );
由于
snprintf
总是写入空终止符(除非指定的最大大小为0
)。通过避免动态分配,可以大大简化程序(一个struct dirent
有一个小的固定大小:名称加上几个整数),vidbuf
不需要比PATH\u MAX长(但如果内存非常紧张,可以使用预计算的值,比如20,并测试snprintf()的返回值)
#包括
#包括
#包括
void do_stuff(char*dev);
void do_stuff(char*dev)
{
DIR*dirp;
结构方向输入buf,*dp;
char vidpath[PATH_MAX];
dirp=opendir(dev);
如果(!dirp)返回;
而(!readdir_r(dirp,&entbuf,&dp)){
如果(!dp)中断;
如果(memcmp(dp->d_name,“video”,strlen(“video”))继续;
snprintf(vidpath,vidpath的大小,“%s/%s”,dev,dp->d_name);
//现在执行打印缓冲区的操作。。。
fprintf(stderr,“是:%s\n”,vidpath);
}
closedir(dirp);
}
内部主(空)
{
做事(“/dev”);
返回0;
}
#include <stdio.h>
#include <string.h>
#include <dirent.h>
void do_stuff(char * dev);
void do_stuff(char * dev)
{
DIR *dirp;
struct dirent entbuf, *dp;
char vidpath[ PATH_MAX ];
dirp = opendir(dev);
if (!dirp ) return;
while ( !readdir_r(dirp, &entbuf, &dp) ) {
if ( !dp ) break;
if ( memcmp( dp->d_name, "video", strlen("video") ) ) continue;
snprintf( vidpath,sizeof vidpath, "%s/%s", dev, dp->d_name );
// Now do an operation that prints the buffer...
fprintf(stderr, "Yes: %s\n", vidpath );
}
closedir( dirp );
}
int main(void)
{
do_stuff ( "/dev" );
return 0;
}