本文整理汇总了C++中readdir函数的典型用法代码示例。如果您正苦于以下问题:C++ readdir函数的具体用法?C++ readdir怎么用?C++ readdir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了readdir函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: opendir
void ModelDB::parseModelFileDir(string dirName){
#ifdef USE_GCC
DIR * dirp = opendir(dirName.c_str());
struct dirent * dp;
ifstream fin(dirName.c_str());
// if the path is a directory, parse the each model in this directory
// ASSUMPTION: here it is only a two tier structure. no recursive reading.
if (dirp) {
errno = 0;
// read each file
while (( dp = readdir(dirp)) != NULL) {
// if the file is . or .., skip it
if(!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")){
continue; // do nothing for "useless" directories
}
// if the file ends with ~, skip it also
if (dp->d_name[strlen(dp->d_name)-1]=='~') {
continue;
}
// otherwise, use the fileName as the modelID
string modelID(dp->d_name);
string fullpath=dirName+"/"+dp->d_name;
// parse the single model file then
parseSingleModelFile(fullpath, modelID);
}
}
// if the path is a file, use the file name as the modelID
else if (fin) {
bDir = false;
int pos = dirName.find_last_of("/");
if (pos!=-1) {
string modelID(dirName.substr(pos+1));
parseSingleModelFile(dirName,modelID);
}
else {
parseSingleModelFile(dirName,dirName);
}
}
// otherwise, error msg
else{
cerr << "\n parseDirectoryModel: Can't open directory " << dirName << endl;
exit (1);
}
#endif //USE_GCC
#ifdef _MSC_VER
// I couldn't find good apis to read a directory. If this is the only
// way, then I don't understand why microsoft doesn't provide a better
// wrapper for these functions. -- Bing Bai.
long hfile = -1;
int status = 0;
char fullpath[MAXPATHLEN] = {0};
int curDrive;
char curPath[MAXPATHLEN];
// store the information of the file/directory
struct stat st;
// preprocess the name, get rid the last char if it is '\'
if(dirName.at(dirName.length()-1)=='\\') {
dirName = dirName.substr(0, dirName.length()-1);
}
// if it is not empty
if( stat(dirName.c_str(), &st)==0 ){
// if is a directory
if (st.st_mode & _S_IFDIR) {
// keep the current driver and path info
curDrive = _getdrive();
_getcwd(curPath, MAXPATHLEN);
// go into the directory
status = _chdir(dirName.c_str());
// check each file in the directory
SearchDirectory((char*)dirName.c_str());
// go back to the original place
_chdrive(curDrive);
_chdir(curPath);
}
// if it is a file
else {
bDir = false;
int pos = dirName.find_last_of("\\");
if (pos!=-1) {
string modelID(dirName.substr(pos+1));
parseSingleModelFile(dirName,modelID);
}
else {
parseSingleModelFile(dirName,dirName);
}
}
}
#endif //_MSC_VER
}
示例2: main
int
main(int argc, char *argv[])
{
MPLS_PL *pl;
int opt;
int ii, pl_ii;
MPLS_PL *pl_list[1000];
struct stat st;
str_t path = {0,};
DIR *dir = NULL;
do {
opt = getopt(argc, argv, OPTS);
switch (opt) {
case -1:
break;
case 'v':
verbose = 1;
break;
case 'l':
clip_list = 1;
break;
case 'i':
playlist_info = 1;
break;
case 'c':
chapter_marks = 1;
break;
case 'd':
dups = 1;
break;
case 'r':
repeats = atoi(optarg);
break;
case 'f':
repeats = 2;
dups = 1;
seconds = 120;
break;
case 's':
seconds = atoi(optarg);
break;
default:
_usage(argv[0]);
break;
}
} while (opt != -1);
if (optind >= argc) {
_usage(argv[0]);
}
for (pl_ii = 0, ii = optind; pl_ii < 1000 && ii < argc; ii++) {
if (stat(argv[ii], &st)) {
continue;
}
dir = NULL;
if (S_ISDIR(st.st_mode)) {
printf("Directory: %s:\n", argv[ii]);
_make_path(&path, argv[ii], "PLAYLIST");
if (path.buf == NULL) {
fprintf(stderr, "Failed to find playlist path: %s\n", argv[ii]);
continue;
}
dir = opendir(path.buf);
if (dir == NULL) {
fprintf(stderr, "Failed to open dir: %s\n", path.buf);
str_free(&path);
continue;
}
}
if (dir != NULL) {
char **dirlist = calloc(10001, sizeof(char*));
struct dirent *ent;
int jj = 0;
for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
if (ent->d_name != NULL) {
dirlist[jj++] = strdup(ent->d_name);
}
}
qsort(dirlist, jj, sizeof(char*), _qsort_str_cmp);
for (jj = 0; dirlist[jj] != NULL; jj++) {
str_t name = {0,};
str_printf(&name, "%s/%s", path.buf, dirlist[jj]);
free(dirlist[jj]);
if (stat(name.buf, &st)) {
str_free(&name);
continue;
}
if (!S_ISREG(st.st_mode)) {
str_free(&name);
//.........这里部分代码省略.........
示例3: inotify_test
static int inotify_test(void)
{
int inotify_fd;
DIR *director_watch;
struct dirent *de;
inotify_fd = open_inotify_fd();
if (inotify_fd > 0) {
/* We will need a place to enqueue inotify events,
this is needed because if you do not read events
fast enough, you will miss them. This queue is
probably too small if you are monitoring something
like a directory with a lot of files and the directory
is deleted.
*/
queue_t q;
q = queue_create(128);
/* This is the watch descriptor returned for each item we are
watching. A real application might keep these for some use
in the application. This sample only makes sure that none of
the watch descriptors is less than 0.
*/
/* Watch all events (IN_ALL_EVENTS) for the directories and
files passed in as arguments.
Read the article for why you might want to alter this for
more efficient inotify use in your app.
*/
int index;
wd = 0;
printf("\n");
/* for (index = 1; (index < argc) && wd >= 0); index++) { */
/* wd = watch_dir(inotify_fd, argv[index], IN_ALL_EVENTS); */
/* } */
director_watch = opendir(WATCH_PATH);
if (director_watch == 0)
return;
while((de = readdir(director_watch)) != 0) {
if(bad_name(de->d_name))
continue;
snprintf(busname, sizeof busname, "%s/%s", WATCH_PATH, de->d_name);
int wd = watch_dir(inotify_fd, busname, IN_DELETE | IN_CREATE);
if (wd > 0){
LOG("chiplua add %s", busname);
}
process_inotify_events(q, inotify_fd);
}
return 0;
}
/* wd = watch_dir(inotify_fd, WATCH_PATH, IN_DELETE | IN_CREATE); */
/* if (wd > 0) { */
/* /\* Wait for events and process them until a */
/* temination condition is detected. */
/* *\/ */
/* process_inotify_events(q, inotify_fd); */
/* } */
/* printf("\nTerminating\n"); */
/* /\* Finish up by closing the fd, destroying the queue, */
/* and returning a proper code. */
/* *\/ */
/* close_inotify_fd(inotify_fd); */
/*queue_destroy(q); */
}
示例4: find_all_disks
static void
find_all_disks (void)
{
DIR *dir;
struct dirent *d;
size_t nr_disks = 0, nr_removable = 0;
dev_t root_device = 0;
struct stat statbuf;
if (stat ("/", &statbuf) == 0)
root_device = statbuf.st_dev;
/* The default list of disks is everything in /sys/block which
* matches the common patterns for disk names.
*/
dir = opendir ("/sys/block");
if (!dir) {
perror ("opendir");
exit (EXIT_FAILURE);
}
for (;;) {
errno = 0;
d = readdir (dir);
if (!d) break;
if (STRPREFIX (d->d_name, "cciss!") ||
STRPREFIX (d->d_name, "hd") ||
STRPREFIX (d->d_name, "sd") ||
STRPREFIX (d->d_name, "ubd") ||
STRPREFIX (d->d_name, "vd")) {
char *p;
/* Skip the device containing the root filesystem. */
if (device_contains (d->d_name, root_device))
continue;
nr_disks++;
all_disks = realloc (all_disks, sizeof (char *) * (nr_disks + 1));
if (!all_disks) {
perror ("realloc");
exit (EXIT_FAILURE);
}
all_disks[nr_disks-1] = strdup (d->d_name);
/* cciss device /dev/cciss/c0d0 will be /sys/block/cciss!c0d0 */
p = strchr (all_disks[nr_disks-1], '!');
if (p) *p = '/';
all_disks[nr_disks] = NULL;
}
else if (STRPREFIX (d->d_name, "sr")) {
nr_removable++;
all_removable = realloc (all_removable,
sizeof (char *) * (nr_removable + 1));
if (!all_removable) {
perror ("realloc");
exit (EXIT_FAILURE);
}
all_removable[nr_removable-1] = strdup (d->d_name);
all_removable[nr_removable] = NULL;
}
}
/* Check readdir didn't fail */
if (errno != 0) {
perror ("readdir: /sys/block");
exit (EXIT_FAILURE);
}
/* Close the directory handle */
if (closedir (dir) == -1) {
perror ("closedir: /sys/block");
exit (EXIT_FAILURE);
}
if (all_disks)
qsort (all_disks, nr_disks, sizeof (char *), compare);
if (all_removable)
qsort (all_removable, nr_removable, sizeof (char *), compare);
}
示例5: main
int main (int argc, char *argv[])
{
char c;
char plugins[100][100], s[20];
char romfile[PATH_MAX];
int old_i, i, i1, i2, i3, i4;
int p, p_fullscreen = 0, p_emumode = 0, p_gfx = 0, p_audio = 0, p_input = 0, p_rsp = 0, p_help = 0, p_error = 0;
int p_emumode_value=1, fileloaded = 0, p_interactive = 0;
int true = 1;
char *buffer, *buffer2;
#if defined (__linux__)
if (signal(SIGTERM, sigterm_handler) == SIG_ERR)
printf("Warning: Couldn't register SIGTERM signal handler!\n");
#endif
//Set working dir
#ifdef WITH_HOME
{
char temp[PATH_MAX], orig[PATH_MAX];
FILE *src, *dest;
struct dirent *entry;
DIR *dir;
strcpy(g_WorkingDir, getenv("HOME"));
strcat(g_WorkingDir, "/.mupen64/");
strcpy(cwd, g_WorkingDir);
mkdir(g_WorkingDir, 0700);
strcpy(temp, g_WorkingDir);
strcat(temp, "mupen64.ini");
dest = fopen(temp, "rb");
if (dest == NULL)
{
unsigned char byte;
dest = fopen(temp, "wb");
strcpy(orig, WITH_HOME);
strcat(orig, "share/mupen64/mupen64.ini");
src = fopen(orig, "rb");
while(fread(&byte, 1, 1, src))
fwrite(&byte, 1, 1, dest);
fclose(src);
fclose(dest);
}
else fclose(dest);
strcpy(temp, g_WorkingDir);
strcat(temp, "lang");
strcpy(orig, WITH_HOME);
strcat(orig, "share/mupen64/lang");
symlink(orig, temp);
/*strcpy(temp, g_WorkingDir);
strcat(temp, "plugins");
strcpy(orig, WITH_HOME);
strcat(orig, "share/mupen64/plugins");
symlink(orig, temp);*/
strcpy(temp, g_WorkingDir);
strcat(temp, "plugins");
mkdir(temp, 0700);
strcpy(orig, WITH_HOME);
strcat(orig, "share/mupen64/plugins");
dir = opendir(orig);
while((entry = readdir(dir)) != NULL)
{
if(strcmp(entry->d_name + strlen(entry->d_name) - 3, ".so"))
{
strcpy(orig, WITH_HOME);
strcat(orig, "share/mupen64/plugins/");
strcat(orig, entry->d_name);
src = fopen(orig, "rb");
if(src == NULL) continue;
strcpy(temp, g_WorkingDir);
strcat(temp, "plugins/");
strcat(temp, entry->d_name);
dest = fopen(temp, "rb");
if(dest == NULL)
{
unsigned char byte;
dest = fopen(temp, "wb");
while(fread(&byte, 1, 1, src))
fwrite(&byte, 1, 1, dest);
fclose(src);
fclose(dest);
}
else fclose(dest);
}
else
{
strcpy(temp, g_WorkingDir);
strcat(temp, "plugins/");
strcat(temp, entry->d_name);
strcpy(orig, WITH_HOME);
strcat(orig, "share/mupen64/plugins/");
strcat(orig, entry->d_name);
symlink(orig, temp);
}
}
//.........这里部分代码省略.........
示例6: findVideoDevice
char * findVideoDevice(const char *name)
{
if(name == NULL) return NULL;
DIR * d;
char * video_pattern = "video";
size_t video_pattern_len = strlen(video_pattern);
size_t name_len = strlen(name);
char * dir_name = "/dev/";
char * result = NULL;
printf("[UVC Cam ] Start finding video device\n");
d = opendir (dir_name);
if (! d) {
fprintf (stderr, "Cannot open directory '%s': %s\n",
dir_name, strerror (errno));
exit (EXIT_FAILURE);
}
while (1) {
try{
struct dirent * entry;
entry = readdir (d);
if (! entry) {
break;
}
// if it is not a video device continue
if(strncmp(video_pattern,entry->d_name,video_pattern_len)!=0) {
continue;
}
// if video device name is not correct, coninue
char * device = (char*) malloc(strlen(dir_name)+strlen(entry->d_name)+1);
strcpy(device,dir_name);
strcat(device, entry->d_name);
printf("device=%s\n",device);
printf("entry->d_name=%s\n",entry->d_name);
int fd = open(device, O_RDWR|O_NONBLOCK);
printf("FIND VIDEO DEVIC, FD is %d\n",fcntl(fd, F_GETFD));
if (fd < 0) {
printf("fd = -1\n");
free(device);
continue;
}
struct v4l2_capability info;
memset(&info, 0x0, sizeof(info));
int res = ioctl(fd, VIDIOC_QUERYCAP, &info);
close(fd);
if (res < 0 || strncmp(name,(char*)info.card,name_len)!=0)
{
printf("name=%s\n",name);
printf("info.card=%s",(char*)info.card);
printf("Error res is %d",res);
free(device);
continue;
}
result = device;
}catch(...){
continue;
}
}
if (closedir (d)) {
fprintf (stderr, "Could not close '%s': %s\n",
dir_name, strerror (errno));
exit (EXIT_FAILURE);
}
printf("[UVC Cam] find video device OK result is %s\n", result);
return result;
}
示例7: while
void MainWindow::on_object_id_textChanged(const QString &arg1)
{
// show all faces allready taged with the id of the object_id field
QString id = ui->object_id->text();
std::vector<QPixmap> listCrops;
QString dir_name = Manager::exemplar()->selectedDirectory;//"/home/daniel/BaoDataBase/myDataBase";
// collect all FaceObjects and imagees with the given id
DIR *dir;
struct dirent *ent;
struct stat info;
const char *c_str2 = dir_name.toLocal8Bit().data();
if ((dir = opendir (c_str2)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
stat(ent->d_name, &info);
//if(!S_ISDIR (info.st_mode)) {
//qDebug() << ent->d_name;
std::vector<FaceObject> list = readObjectFile(dir_name.toStdString() + "/.metaface/" + ent->d_name + ".txt");
if(list.size() > 0) {
for(std::vector<FaceObject>::iterator it = list.begin(); it != list.end(); ++it) {
FaceObject fo = *it;
if(fo.objectID == id.toStdString()) {
qDebug() << "found a face in:" << ent->d_name;
QPixmap * img = new QPixmap();
QString fileName = QString::fromStdString(ent->d_name);
img->load(dir_name + "/" + fileName);
//QPixmap::copy(int x, int y, int width, int height )
QPixmap imgCroped = img->copy(fo.x, fo.y, fo.width, fo.height);
qDebug() << "image crop x:" << fo.x << "y:" << fo.y << "width" << fo.width << "height:" << fo.height;
listCrops.push_back(imgCroped);
}
}
}
}
closedir (dir);
}
// check how many croped faces are stored in the list
qDebug() << "there are " << listCrops.size() << " store in the vector";
//QString imgPath = "/home/daniel/facetag/datasettools2/datasettools80.png";
//QImage *img = new QImage();
//bool loaded = img->load(imgPath);
//if (loaded)
//{
/*QTableWidgetItem *thumbnail = new QTableWidgetItem;
thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img));
//thumbnailsWidget->setColumnCount(3);
//thumbnailsWidget->setRowCount(3);
ui->tableIamges->setItem(0, 0, thumbnail);*/
//w.setCentralWidget(thumbnailsWidget);
//} else {
//qDebug()<<"Image "<<imgPath<<" was not opened!";
// }
int row = 0;
int column = 0;
int cell = 0;
for(std::vector<QPixmap>::iterator it = listCrops.begin(); it != listCrops.end(); ++it) {
QPixmap pm = *it;
pm = pm.scaledToHeight(80,Qt::SmoothTransformation);
QTableWidgetItem *thumbnail = new QTableWidgetItem;
thumbnail->setData(Qt::DecorationRole, pm);
ui->tableIamges->setItem(column, row, thumbnail);
if(column == 2) {
row++;
cell++;
column = 0;
} else {
row++;
cell++;
}
}
int maxCells = ui->tableIamges->rowCount() * ui->tableIamges->columnCount();
while(cell < 9) {
QTableWidgetItem *thumbnail = new QTableWidgetItem;
ui->tableIamges->setItem(column, row, thumbnail);
if(column == 2) {
row++;
cell++;
column = 0;
} else {
row++;
cell++;
}
}
}
示例8: daq_load_modules
DAQ_LINKAGE int daq_load_modules(const char *directory_list[])
{
static const char *extension = MODULE_EXT;
#ifndef WIN32
char dirpath[NAME_SIZE];
DIR *dirp;
struct dirent *de;
char *p;
int ret;
#ifdef STATIC_MODULE_LIST
load_static_modules();
#endif
for (; directory_list && *directory_list; directory_list++)
{
if (!(**directory_list))
continue;
if ((dirp = opendir(*directory_list)) == NULL)
{
fprintf(stderr,"Unable to open directory \"%s\"\n", *directory_list);
continue;
}
DEBUG("Loading modules in: %s\n", *directory_list);
while((de = readdir(dirp)) != NULL)
{
if (de->d_name == NULL)
continue;
p = strrchr(de->d_name, '.');
if (!p || strcmp(p, extension))
continue;
snprintf(dirpath, sizeof(dirpath), "%s/%s", *directory_list, de->d_name);
ret = daq_load_module(dirpath);
if (ret == DAQ_SUCCESS)
{
DEBUG("Found module %s\n", de->d_name);
}
else if (ret == DAQ_ERROR_NOMEM)
{
closedir(dirp);
return DAQ_ERROR_NOMEM;
}
}
closedir(dirp);
}
#else
/* Find all shared library files in path */
char path_buf[PATH_MAX];
char dyn_lib_name[PATH_MAX];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
HANDLE fSearch;
WIN32_FIND_DATA FindFileData;
int pathLen = 0;
const char *directory;
int useDrive = 0;
#ifdef STATIC_MODULE_LIST
load_static_modules();
#endif
for (; directory_list && *directory_list; directory_list++)
{
if (!(**directory_list))
continue;
if ((strncpy(path_buf, *directory_list, PATH_MAX) == NULL) ||
(strlen(path_buf) != strlen(*directory_list)))
{
fprintf(stderr, "Path is too long: %s\n", *directory_list);
continue;
}
pathLen = strlen(path_buf);
if ((path_buf[pathLen - 1] == '\\') ||
(path_buf[pathLen - 1] == '/'))
{
/* A directory was specified with trailing dir character */
_splitpath(path_buf, drive, dir, fname, ext);
_makepath(path_buf, drive, dir, "*", MODULE_EXT);
directory = &dir[0];
useDrive = 1;
}
else /* A directory was specified */
{
_splitpath(path_buf, drive, dir, fname, ext);
if (strcmp(extension, ""))
{
fprintf(stderr, "Improperly formatted directory name: %s\n", *directory_list);
continue;
}
_makepath(path_buf, "", path_buf, "*", MODULE_EXT);
directory = *directory_list;
}
//.........这里部分代码省略.........
示例9: main
int main(){
int i,line;
char content[MAX_SCHEDULER][MAXLINE];
int pipe_fd[2];
FILE* fptr,*tmp_fptr;
struct dirent *dirp;
DIR* dp;
pid_t pid;
if((dp=opendir(dirname))==NULL)
err_sys();
while((dirp=readdir(dp))!=NULL)
if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
continue;
else
break;
if(dirp==NULL)
_Exit(0);
if((tmp_fptr=fopen(tmp_filename,"w"))==NULL)
err_sys();
if(pipe(pipe_fd)<0)
err_sys();
if((pid=fork())<0){
err_sys();
}else if(pid>0){ //parent , read from pipe
close(pipe_fd[1]);
if((fptr=fdopen(pipe_fd[0],"r"))==NULL)
err_sys();
for(line=0;fgets(content[line],MAXLINE,fptr)>0;line++);
if(fclose(fptr)==-1)
err_sys();
if(waitpid(pid,NULL,0)<0)
err_sys();
}else{ //child , write to pipe
close(pipe_fd[0]);
if(pipe_fd[1] != STDOUT_FILENO){
if(dup2(pipe_fd[1],STDOUT_FILENO) != STDOUT_FILENO)
err_sys();
close(pipe_fd[1]);
}
if(execl("/usr/bin/crontab","crontab","-l",NULL)<0)
err_sys();
}
deal_content(content,&line,dp,dirp);
if(closedir(dp))
err_sys();
for(i=0;i<line;i++)
fprintf(tmp_fptr,"%s",content[i]);
if(fclose(tmp_fptr)==-1)
err_sys();
if((pid=fork())<0){
err_sys();
}else if(pid>0){ //parent
if(waitpid(pid,NULL,0)<0)
err_sys();
}else{ //child
if(execl("/usr/bin/crontab","crontab",tmp_filename,NULL)<0)
err_sys();
}
if(unlink(tmp_filename)==-1)
err_sys();
return 0;
}
示例10: __populate_fs
/* Copy files from source_dir to fs */
static errcode_t __populate_fs(ext2_filsys fs, ext2_ino_t parent_ino,
const char *source_dir, ext2_ino_t root,
struct hdlinks_s *hdlinks)
{
const char *name;
DIR *dh;
struct dirent *dent;
struct stat st;
char ln_target[PATH_MAX];
unsigned int save_inode;
ext2_ino_t ino;
errcode_t retval;
int read_cnt;
int hdlink;
if (chdir(source_dir) < 0) {
com_err(__func__, errno,
_("while changing working directory to \"%s\""),
source_dir);
return errno;
}
if (!(dh = opendir("."))) {
com_err(__func__, errno,
_("while opening directory \"%s\""), source_dir);
return errno;
}
while ((dent = readdir(dh))) {
if ((!strcmp(dent->d_name, ".")) ||
(!strcmp(dent->d_name, "..")))
continue;
lstat(dent->d_name, &st);
name = dent->d_name;
/* Check for hardlinks */
save_inode = 0;
if (!S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode) &&
st.st_nlink > 1) {
hdlink = is_hardlink(hdlinks, st.st_dev, st.st_ino);
if (hdlink >= 0) {
retval = add_link(fs, parent_ino,
hdlinks->hdl[hdlink].dst_ino,
name);
if (retval) {
com_err(__func__, retval,
"while linking %s", name);
return retval;
}
continue;
} else
save_inode = 1;
}
switch(st.st_mode & S_IFMT) {
case S_IFCHR:
case S_IFBLK:
case S_IFIFO:
retval = do_mknod_internal(fs, parent_ino, name, &st);
if (retval) {
com_err(__func__, retval,
_("while creating special file "
"\"%s\""), name);
return retval;
}
break;
case S_IFSOCK:
/* FIXME: there is no make socket function atm. */
com_err(__func__, 0,
_("ignoring socket file \"%s\""), name);
continue;
case S_IFLNK:
read_cnt = readlink(name, ln_target,
sizeof(ln_target));
if (read_cnt == -1) {
com_err(__func__, errno,
_("while trying to readlink \"%s\""),
name);
return errno;
}
ln_target[read_cnt] = '\0';
retval = do_symlink_internal(fs, parent_ino, name,
ln_target, root);
if (retval) {
com_err(__func__, retval,
_("while writing symlink\"%s\""),
name);
return retval;
}
break;
case S_IFREG:
retval = do_write_internal(fs, parent_ino, name, name,
root);
if (retval) {
com_err(__func__, retval,
_("while writing file \"%s\""), name);
return retval;
}
break;
//.........这里部分代码省略.........
示例11: process_lua
static void process_lua(hs_output_plugins *plugins, const char *lpath,
const char *rpath, DIR *dp)
{
char lua_lpath[HS_MAX_PATH];
char lua_rpath[HS_MAX_PATH];
char cfg_lpath[HS_MAX_PATH];
char cfg_rpath[HS_MAX_PATH];
size_t tlen = strlen(hs_output_dir) + 1;
struct dirent *entry;
while ((entry = readdir(dp))) {
if (hs_has_ext(entry->d_name, hs_lua_ext)) {
// move the Lua to the run directory
if (!hs_get_fqfn(lpath, entry->d_name, lua_lpath, sizeof(lua_lpath))) {
hs_log(NULL, g_module, 0, "load lua path too long");
exit(EXIT_FAILURE);
}
if (!hs_get_fqfn(rpath, entry->d_name, lua_rpath, sizeof(lua_rpath))) {
hs_log(NULL, g_module, 0, "run lua path too long");
exit(EXIT_FAILURE);
}
if (rename(lua_lpath, lua_rpath)) {
hs_log(NULL, g_module, 3, "failed to move: %s to %s errno: %d",
lua_lpath, lua_rpath, errno);
continue;
}
// restart any plugins using this Lua code
pthread_mutex_lock(&plugins->list_lock);
for (int i = 0; i < plugins->list_cap; ++i) {
if (!plugins->list[i]) continue;
hs_output_plugin *p = plugins->list[i];
if (strcmp(lua_rpath, lsb_heka_get_lua_file(p->hsb)) == 0) {
int ret = snprintf(cfg_lpath, HS_MAX_PATH, "%s/%s%s", lpath,
p->name + tlen, hs_cfg_ext);
if (ret < 0 || ret > HS_MAX_PATH - 1) {
hs_log(NULL, g_module, 0, "load cfg path too long");
exit(EXIT_FAILURE);
}
ret = snprintf(cfg_rpath, HS_MAX_PATH, "%s/%s%s", rpath,
p->name + tlen, hs_cfg_ext);
if (ret < 0 || ret > HS_MAX_PATH - 1) {
hs_log(NULL, g_module, 0, "run cfg path too long");
exit(EXIT_FAILURE);
}
// if no new cfg was provided, move the existing cfg to the load
// directory
if (!hs_file_exists(cfg_lpath)) {
if (rename(cfg_rpath, cfg_lpath)) {
hs_log(NULL, g_module, 3, "failed to move: %s to %s errno: %d",
cfg_rpath, cfg_lpath, errno);
}
}
}
}
pthread_mutex_unlock(&plugins->list_lock);
}
}
rewinddir(dp);
}
示例12: zed_conf_scan_dir
/*
* Scan the [zcp] zedlet_dir for files to exec based on the event class.
* Files must be executable by user, but not writable by group or other.
* Dotfiles are ignored.
*
* Return 0 on success with an updated set of zedlets,
* or -1 on error with errno set.
*
* FIXME: Check if zedlet_dir and all parent dirs are secure.
*/
int
zed_conf_scan_dir(struct zed_conf *zcp)
{
zed_strings_t *zedlets;
DIR *dirp;
struct dirent *direntp;
char pathname[PATH_MAX];
struct stat st;
int n;
if (!zcp) {
errno = EINVAL;
zed_log_msg(LOG_ERR, "Failed to scan zedlet dir: %s",
strerror(errno));
return (-1);
}
zedlets = zed_strings_create();
if (!zedlets) {
errno = ENOMEM;
zed_log_msg(LOG_WARNING, "Failed to scan dir \"%s\": %s",
zcp->zedlet_dir, strerror(errno));
return (-1);
}
dirp = opendir(zcp->zedlet_dir);
if (!dirp) {
int errno_bak = errno;
zed_log_msg(LOG_WARNING, "Failed to open dir \"%s\": %s",
zcp->zedlet_dir, strerror(errno));
zed_strings_destroy(zedlets);
errno = errno_bak;
return (-1);
}
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] == '.')
continue;
n = snprintf(pathname, sizeof (pathname),
"%s/%s", zcp->zedlet_dir, direntp->d_name);
if ((n < 0) || (n >= sizeof (pathname))) {
zed_log_msg(LOG_WARNING, "Failed to stat \"%s\": %s",
direntp->d_name, strerror(ENAMETOOLONG));
continue;
}
if (stat(pathname, &st) < 0) {
zed_log_msg(LOG_WARNING, "Failed to stat \"%s\": %s",
pathname, strerror(errno));
continue;
}
if (!S_ISREG(st.st_mode)) {
zed_log_msg(LOG_INFO,
"Ignoring \"%s\": not a regular file",
direntp->d_name);
continue;
}
if ((st.st_uid != 0) && !zcp->do_force) {
zed_log_msg(LOG_NOTICE,
"Ignoring \"%s\": not owned by root",
direntp->d_name);
continue;
}
if (!(st.st_mode & S_IXUSR)) {
zed_log_msg(LOG_INFO,
"Ignoring \"%s\": not executable by user",
direntp->d_name);
continue;
}
if ((st.st_mode & S_IWGRP) && !zcp->do_force) {
zed_log_msg(LOG_NOTICE,
"Ignoring \"%s\": writable by group",
direntp->d_name);
continue;
}
if ((st.st_mode & S_IWOTH) && !zcp->do_force) {
zed_log_msg(LOG_NOTICE,
"Ignoring \"%s\": writable by other",
direntp->d_name);
continue;
}
if (zed_strings_add(zedlets, NULL, direntp->d_name) < 0) {
zed_log_msg(LOG_WARNING,
"Failed to register \"%s\": %s",
direntp->d_name, strerror(errno));
continue;
}
if (zcp->do_verbose)
zed_log_msg(LOG_INFO,
"Registered zedlet \"%s\"", direntp->d_name);
}
if (closedir(dirp) < 0) {
int errno_bak = errno;
//.........这里部分代码省略.........
示例13: dumpDirectoryContentsIntoRawFile
void dumpDirectoryContentsIntoRawFile(char *dir, int fd) {
DIR *FD = NULL;
struct dirent *in_file;
char *imagePath;
// loop over image stack - in order //
if (NULL == (FD = opendir(dir)))
{
fprintf(stderr, "Error : Failed to open input directory - %s\n", strerror(errno));
free(FD);
return;
}
while ((in_file = readdir(FD)))
{
printf("Processing %s\n", in_file->d_name);
if (!strcmp (in_file->d_name, "."))
continue;
if (!strcmp (in_file->d_name, ".."))
continue;
//APPLE Dir ISSUE
if (!strcmp (in_file->d_name, ".DS_Store"))
continue;
asprintf(&imagePath, "%s/%s", dir, in_file->d_name);
appendImageBytesToRaw(fd, imagePath);
}
closedir(FD);
// loop over image stack - strange behaviour (revise order) //
/*
int n;
struct dirent **namelist;
n = scandir(dir, &namelist, 0, alphasort);
// error scanning directory
if (n < 0) {
perror("scandir");
exit(-1);
}
*/
/*
while(n--) {
printf("Processing %s\n", namelist[n]->d_name);
if (!strcmp (namelist[n]->d_name, "."))
continue;
if (!strcmp (namelist[n]->d_name, ".."))
continue;
//APPLE Dir ISSUE
if (!strcmp (namelist[n]->d_name, ".DS_Store"))
continue;
asprintf(&imagePath, "%s/%s", dir, namelist[n]->d_name);
appendImageBytesToRaw(fd, imagePath);
free(namelist[n]);
}
free(namelist);
*/
}
示例14: fn_filename_completion_function
/*
* return first found file name starting by the ``text'' or NULL if no
* such file can be found
* value of ``state'' is ignored
*
* it's the caller's responsibility to free the returned string
*/
char *
fn_filename_completion_function(const char *text, int state)
{
static DIR *dir = NULL;
static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
static size_t filename_len = 0;
struct dirent *entry;
char *temp;
size_t len;
if (state == 0 || dir == NULL) {
temp = strrchr(text, '/');
if (temp) {
char *nptr;
temp++;
nptr = el_realloc(filename, (strlen(temp) + 1) *
sizeof(*nptr));
if (nptr == NULL) {
el_free(filename);
filename = NULL;
return NULL;
}
filename = nptr;
(void)strcpy(filename, temp);
len = (size_t)(temp - text); /* including last slash */
nptr = el_realloc(dirname, (len + 1) *
sizeof(*nptr));
if (nptr == NULL) {
el_free(dirname);
dirname = NULL;
return NULL;
}
dirname = nptr;
(void)strncpy(dirname, text, len);
dirname[len] = '\0';
} else {
el_free(filename);
if (*text == 0)
filename = NULL;
else {
filename = strdup(text);
if (filename == NULL)
return NULL;
}
el_free(dirname);
dirname = NULL;
}
if (dir != NULL) {
(void)closedir(dir);
dir = NULL;
}
/* support for ``~user'' syntax */
el_free(dirpath);
dirpath = NULL;
if (dirname == NULL) {
if ((dirname = strdup("")) == NULL)
return NULL;
dirpath = strdup("./");
} else if (*dirname == '~')
dirpath = fn_tilde_expand(dirname);
else
dirpath = strdup(dirname);
if (dirpath == NULL)
return NULL;
dir = opendir(dirpath);
if (!dir)
return NULL; /* cannot open the directory */
/* will be used in cycle */
filename_len = filename ? strlen(filename) : 0;
}
/* find the match */
while ((entry = readdir(dir)) != NULL) {
/* skip . and .. */
if (entry->d_name[0] == '.' && (!entry->d_name[1]
|| (entry->d_name[1] == '.' && !entry->d_name[2])))
continue;
if (filename_len == 0)
break;
/* otherwise, get first entry where first */
/* filename_len characters are equal */
if (entry->d_name[0] == filename[0]
/* Some dirents have d_namlen, but it is not portable. */
&& strlen(entry->d_name) >= filename_len
&& strncmp(entry->d_name, filename,
filename_len) == 0)
//.........这里部分代码省略.........
示例15: while
std::vector<std::string> SerialInterface::enumerate_ports()
{
std::vector<std::string> SerialDeviceList = std::vector<std::string>();
#ifdef __unix__
DIR *dp;
struct dirent *dirp;
std::string f, d;
std::vector<std::string>::iterator it;
char buf[PATH_MAX];
struct serial_struct serinfo;
int fd;
if ((dp = opendir("/dev/")) == NULL)
{
std::cerr << "Error (" << errno << ") opening /dev/" << std::endl;
}
else
{
while ((dirp = readdir(dp)) != NULL)
{
f = dirp->d_name;
d = "/dev/" + f;
if (f.find("ttyS") == 0)
{
if ((fd = ::open(d.c_str(), O_RDWR|O_NONBLOCK)) < 0)
{
std::cerr << "Cannot open port " << d << std::endl;
continue;
}
serinfo.reserved_char[0] = 0;
if (::ioctl(fd, TIOCGSERIAL, &serinfo) < 0)
{
std::cerr << "Cannot get serial info for " << d << std::endl;
::close(fd);
continue;
}
if (serinfo.port != 0)
SerialDeviceList.push_back(d);
::close(fd);
continue;
}
if (f.find("ttyUSB") == 0)
{
SerialDeviceList.push_back(d);
}
}
closedir(dp);
}
if ((dp = opendir("/dev/serial/by-id/")) != NULL)
{
while ((dirp = readdir(dp)) != NULL)
{
f = dirp->d_name;
if (f == "." || f == "..")
continue;
f = "/dev/serial/by-id/" + f;
if (realpath(f.c_str(), buf));
{
f = buf;
SerialDeviceList.push_back(f);
}
}
closedir(dp);
}
#elif defined _WIN32
TCHAR szDevices[65535];
unsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535);
TCHAR *ptr = szDevices;
TCHAR *temp_ptr;
std::string c;
while (dwChars)
{
int port;
if (sscanf(ptr, "COM%d", &port) == 1)
{
c = ptr;
SerialDeviceList.push_back(c);
}
temp_ptr = strchr(ptr, 0);
dwChars -= (DWORD)((temp_ptr - ptr) / sizeof(TCHAR) + 1);
ptr = temp_ptr + 1;
}
#endif
//.........这里部分代码省略.........