Exemplo n.º 1
0
Arquivo: C.c Projeto: mattn/C-win32
static void cleanup(void)
{
  if (! keep_files) {
    if (temp_dir != NULL) {
      remove_dir(temp_dir);
    }
  }
}
Exemplo n.º 2
0
/*===========================================================================*
 *				fs_unlink				     *
 *===========================================================================*/
int fs_unlink()
{
/* Perform the unlink(name) or rmdir(name) system call. The code for these two
 * is almost the same.  They differ only in some condition testing.  Unlink()
 * may be used by the superuser to do dangerous things; rmdir() may not.
 */
  register struct inode *rip;
  struct inode *rldirp;
  int r;
  char string[NAME_MAX + 1];
  phys_bytes len;

  /* Copy the last component */
  len = fs_m_in.REQ_PATH_LEN; /* including trailing '\0' */
  if (len > NAME_MAX + 1 || len > EXT2_NAME_MAX + 1)
	return(ENAMETOOLONG);

  r = sys_safecopyfrom(VFS_PROC_NR, (cp_grant_id_t) fs_m_in.REQ_GRANT,
                       (vir_bytes) 0, (vir_bytes) string, (size_t) len);
  if (r != OK) return r;
  NUL(string, len, sizeof(string));

  /* Temporarily open the dir. */
  if( (rldirp = get_inode(fs_dev, (ino_t) fs_m_in.REQ_INODE_NR)) == NULL)
	  return(EINVAL);

  /* The last directory exists.  Does the file also exist? */
  rip = advance(rldirp, string, IGN_PERM);
  r = err_code;

  /* If error, return inode. */
  if(r != OK) {
	/* Mount point? */
	if (r == EENTERMOUNT || r == ELEAVEMOUNT) {
		put_inode(rip);
		r = EBUSY;
	}
	put_inode(rldirp);
	return(r);
  }

  /* Now test if the call is allowed, separately for unlink() and rmdir(). */
  if(fs_m_in.m_type == REQ_UNLINK) {
	  /* Only the su may unlink directories, but the su can unlink any
	   * dir.*/
	  if( (rip->i_mode & I_TYPE) == I_DIRECTORY) r = EPERM;

	  /* Actually try to unlink the file; fails if parent is mode 0 etc. */
	  if (r == OK) r = unlink_file(rldirp, rip, string);
  } else {
	  r = remove_dir(rldirp, rip, string); /* call is RMDIR */
  }

  /* If unlink was possible, it has been done, otherwise it has not. */
  put_inode(rip);
  put_inode(rldirp);
  return(r);
}
Exemplo n.º 3
0
/* helper function to remove a non-empty directory */
static int remove_dir(char* dirname, int len)
{
    int result = 0;
    DIR* dir;
    int dirlen = strlen(dirname);

    dir = opendir(dirname);
    if (!dir)
        return -1; /* open error */

    while(true)
    {
        struct dirent* entry;
        /* walk through the directory content */
        entry = readdir(dir);
        if (!entry)
            break;
        struct dirinfo info = dir_get_info(dir, entry);
        dirname[dirlen] ='\0';
        /* inform the user which dir we're deleting */
        splash(0, dirname);

        /* append name to current directory */
        snprintf(dirname+dirlen, len-dirlen, "/%s", entry->d_name);
        if (info.attribute & ATTR_DIRECTORY)
        {   /* remove a subdirectory */
            if (!strcmp((char *)entry->d_name, ".") ||
                !strcmp((char *)entry->d_name, ".."))
                continue; /* skip these */

            result = remove_dir(dirname, len); /* recursion */
            if (result)
                break; /* or better continue, delete what we can? */
        }
        else
        {   /* remove a file */
            draw_slider();
            result = remove(dirname);
        }
        if(ACTION_STD_CANCEL == get_action(CONTEXT_STD,TIMEOUT_NOBLOCK))
        {
            splash(HZ, ID2P(LANG_CANCEL));
            result = -1;
            break;
        }
    }
    closedir(dir);

    if (!result)
    {   /* remove the now empty directory */
        dirname[dirlen] = '\0'; /* terminate to original length */

        result = rmdir(dirname);
    }

    return result;
}
Exemplo n.º 4
0
YETI_Result File::remove(const char * path, bool recurse /* = false */)
{
    FileInfo info;
    YETI_CHECK_WARNING(get_info(path, &info));
    if (info.m_type_ == FileInfo::FILE_TYPE_DIRECTORY) {
        return remove_dir(path, recurse);
    }
    return remove_file(path);
}
Exemplo n.º 5
0
void
test_remove(void)
{
	test_remove_path();

	remove_dir();
	remove_dot();
	remove_dotdot();
	remove_empty();
}
static int inject_second_rd(const char *path, const char *second_path)
{
    int result = -1;
    uint32_t magic = 0;

    FILE *f = fopen(path, "re");
    if (!f)
    {
        ERROR("Couldn't open %s!\n", path);
        return -1;
    }
    fread(&magic, sizeof(magic), 1, f);
    fclose(f);

    mkdir(TMP_RD2_UNPACKED_DIR, 0755);

    // Decompress initrd
    int type;
    char buff[256];
    char busybox_path[256];
    snprintf(busybox_path, sizeof(busybox_path), "%s/busybox", mrom_dir());

    char *cmd[] = { busybox_path, "sh", "-c", buff, NULL };

    snprintf(buff, sizeof(buff), "B=\"%s\"; cd \"%s\"; \"$B\" cat \"%s\" | \"$B\" cpio -i", busybox_path, TMP_RD2_UNPACKED_DIR, second_path);

    int r;
    char *out = run_get_stdout_with_exit(cmd, &r);
    if (r != 0)
    {
        ERROR("Output: %s\n", out);
        ERROR("Failed to unpack second ramdisk!%s\n", buff);
        goto fail;
    }

    // Update files
    if (copy_rd_files(second_path, busybox_path) < 0)
        goto fail;

    // Pack initrd again
    snprintf(buff, sizeof(buff), "B=\"%s\"; cd \"%s\"; \"$B\" find . | \"$B\" cpio -o -H newc > \"%s\"", busybox_path, TMP_RD2_UNPACKED_DIR, second_path);

    out = run_get_stdout_with_exit(cmd, &r);
    if (r != 0)
    {
        ERROR("Output: %s\n", out);
        ERROR("Failed to pack ramdisk.cpio!\n");
        goto fail;
    }
success:
    result = 0;
fail:
    remove_dir(TMP_RD2_UNPACKED_DIR);
    return result;
}
Exemplo n.º 7
0
Arquivo: dir.c Projeto: antontest/c
/**
 * @brief remove file or dir
 *
 * @param pathname [in] path of file or directoy
 *
 * @return 0, if succ; -1, if failed.
 */
int remove_file(const char *pathname)
{
    struct stat st = {0};
    if (pathname == NULL) return -1;
    if (lstat(pathname, &st) < 0) return -1;

    if (S_ISDIR(st.st_mode)) return remove_dir(pathname);
    else remove(pathname);

    return 0;
}
Exemplo n.º 8
0
static bool remove_all(const char *id)
{
	bool removed;

	remove_file(id, SETTINGS);
	remove_file(id, "data");

	removed = remove_dir(id);
	if (!removed)
		return false;

	return true;
}
Exemplo n.º 9
0
// refresh known data of station and hotspot
void refreshAndZip() {
    // clear known station and hotspot
    int i;
    for (i = 0; i < hotspot_records_count; ++i) {
        memset(knownHotspotMAC[i], 0, sizeof(knownHotspotMAC[i]));
    }

    for (i = 0; i < sta_records_count; ++i) {
        memset(knownStaMAC[i], 0, sizeof(knownStaMAC[i]));
    }

    /* zip
     * -r 递归处理,将指定目录下的所有文件和子目录一并处理。
     * -q 不显示指令执行过程。
    **/
    system("zip -r -q /tmp/group2/zip/data.zip /tmp/group2/data");
    remove_dir("/tmp/group2/data/hotspot");
    hotspot_records_count = 0;
    remove_dir("/tmp/group2/data/station");
    sta_records_count = 0;

}
Exemplo n.º 10
0
static gboolean remove_all(const char *id)
{
	gboolean removed;

	remove_file(id, SETTINGS);
	remove_file(id, "data");

	removed = remove_dir(id);
	if (removed == FALSE)
		return FALSE;

	return TRUE;
}
Exemplo n.º 11
0
int	check_relative_cmd_suite(char *buffer, char *abso,
				 struct s_static_socket *br)
{
  if (strncmp(buffer, "RMD", 3) == 0)
    remove_dir(abso, br, 0);
  else
    if (strncmp(buffer, "DELE", 4) == 0)
      remove_dir(abso, br, 1);
    else
      if (strncmp(buffer, "MKD", 3) == 0)
	make_dir(abso, br);
      else
	if (strncmp(buffer, "SITE", 4) == 0)
	  site_func(buffer, br);
	else
	  if (strncmp(buffer, "RNFR", 4) == 0)
	    rename_from(abso, br);
	  else
	    if (strncmp(buffer, "RNTO", 4) == 0)
	      rename_to(br);
	else
	  return (-1);
  return (0);
}
Exemplo n.º 12
0
Arquivo: C.c Projeto: mattn/C-win32
static void update_cache(void)
{
  DIR* d = NULL;
  struct dirent* e;
  char* cache_root, * oldest_dir = NULL, * filename;
  time_t oldest_mtime = 0; // initialized here only to avoid compiler warning
  int num_files;
  
  num_files = 0;
  
  cache_root = str_concat(str_dup(root_dir), "/cache");
  if ((d = opendir(cache_root)) != NULL) {
    while ((e = readdir(d)) != NULL) {
      struct stat st;
      if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) {
	continue;
      }
      filename = str_concat(str_concat(str_dup(cache_root), "/"), e->d_name);
      if (stat(filename, &st) == 0 && S_ISDIR(st.st_mode)) {
	if (oldest_dir == NULL || st.st_mtime < oldest_mtime) {
	  free(oldest_dir);
	  oldest_dir = str_dup(filename);
	  oldest_mtime = st.st_mtime;
	}
	if (++num_files >= FILES_PER_CACHEDIR && oldest_dir != NULL) {
	  remove_dir(oldest_dir);
	  if (readdir(d) != NULL) {
	    /* more files to come, check again */
	    num_files = 0;
	    free(oldest_dir);
	    oldest_dir = NULL;
	    rewinddir(d);
	  } else {
	    free(filename);
	    break;
	  }
	}
      }
      free(filename);
    }
    closedir(d);
  }
  free(oldest_dir);
  free(cache_root);
}
Exemplo n.º 13
0
int setup_zip(const char *file, char *p)
{
	if (!p)
		return -1;
	fprintf(stderr,"Trying to install: %s\n", file);
	if (unpack(file, p)) {
		if (zip_game_dirname[0]) {
			p = getpath(p, zip_game_dirname);
			fprintf(stderr, "Cleaning: '%s'...\n", p);
			remove_dir(p);
			free(p);
		}
		return -1;
	}
	game_sw = zip_game_dirname;
	games_sw = p;
	return 0;
}
Exemplo n.º 14
0
void sysfs_remove_dir(struct kobject * kobj)
{
	struct list_head * node;
	struct dentry * dentry = dget(kobj->dentry);

	if (!dentry)
		return;

	pr_debug("sysfs %s: removing dir\n",dentry->d_name.name);
	down(&dentry->d_inode->i_sem);

	spin_lock(&dcache_lock);
	node = dentry->d_subdirs.next;
	while (node != &dentry->d_subdirs) {
		struct dentry * d = list_entry(node,struct dentry,d_child);
		list_del_init(node);

		pr_debug(" o %s (%d): ",d->d_name.name,atomic_read(&d->d_count));
		if (d->d_inode) {
			d = dget_locked(d);
			pr_debug("removing");

			/**
			 * Unlink and unhash.
			 */
			spin_unlock(&dcache_lock);
			d_delete(d);
			simple_unlink(dentry->d_inode,d);
			dput(d);
			spin_lock(&dcache_lock);
		}
		pr_debug(" done\n");
		node = dentry->d_subdirs.next;
	}
	list_del_init(&dentry->d_child);
	spin_unlock(&dcache_lock);
	up(&dentry->d_inode->i_sem);

	remove_dir(dentry);
	/**
	 * Drop reference from dget() on entrance.
	 */
	dput(dentry);
}
Exemplo n.º 15
0
/*===========================================================================*
 *				fs_unlink				     *
 *===========================================================================*/
int fs_unlink(ino_t dir_nr, char *name, int call)
{
    /* Perform the unlink(name) or rmdir(name) system call. The code for these two
     * is almost the same.  They differ only in some condition testing.
     */
    register struct inode *rip;
    struct inode *rldirp;
    int r;

    /* Temporarily open the dir. */
    if((rldirp = get_inode(fs_dev, dir_nr)) == NULL)
        return(EINVAL);

    /* The last directory exists.  Does the file also exist? */
    rip = advance(rldirp, name);
    r = err_code;

    /* If error, return inode. */
    if(r != OK) {
        put_inode(rldirp);
        return(r);
    }
    if (rip->i_mountpoint) {
        put_inode(rip);
        put_inode(rldirp);
        return(EBUSY);
    }

    /* Now test if the call is allowed, separately for unlink() and rmdir(). */
    if (call == FSC_UNLINK) {
        if( (rip->i_mode & I_TYPE) == I_DIRECTORY) r = EPERM;

        /* Actually try to unlink the file; fails if parent is mode 0 etc. */
        if (r == OK) r = unlink_file(rldirp, rip, name);
    } else {
        r = remove_dir(rldirp, rip, name); /* call is RMDIR */
    }

    /* If unlink was possible, it has been done, otherwise it has not. */
    put_inode(rip);
    put_inode(rldirp);
    return(r);
}
Exemplo n.º 16
0
int remove_dir(const char *dir)
{
    struct DIR *d = opendir(dir);
    if(!d)
        return -1;

    struct dirent *dt;
    int res = 0;

    int dir_len = strlen(dir) + 1;
    char *n = malloc(dir_len + 1);
    strcpy(n, dir);
    strcat(n, "/");

    while(res == 0 && (dt = readdir(d)))
    {
        if(dt->d_name[0] == '.' && (dt->d_name[1] == '.' || dt->d_name[1] == 0))
            continue;

        n = realloc(n, dir_len + strlen(dt->d_name) + 1);
        n[dir_len] = 0;
        strcat(n, dt->d_name);

        if(dt->d_type == DT_DIR)
        {
            if(remove_dir(n) < 0)
                res = -1;
        }
        else
        {
            if(remove(n) < 0)
                res = -1;
        }
    }

    free(n);
    closedir(d);

    if(res == 0 && remove(dir) < 0)
        res = -1;
    return res;
}
Exemplo n.º 17
0
static int copy_rd_files(UNUSED const char *path, UNUSED const char *busybox_path)
{
    char buf[256];

    if (access(TMP_RD_UNPACKED_DIR"/main_init", F_OK) < 0 &&
        rename(TMP_RD_UNPACKED_DIR"/init", TMP_RD_UNPACKED_DIR"/main_init") < 0)
    {
        ERROR("Failed to move /init to /main_init!\n");
        return -1;
    }

    snprintf(buf, sizeof(buf), "%s/trampoline", mrom_dir());
    if(copy_file(buf, TMP_RD_UNPACKED_DIR"/init") < 0)
    {
        ERROR("Failed to copy trampoline to /init!\n");
        return -1;
    }
    chmod(TMP_RD_UNPACKED_DIR"/init", 0750);

    remove(TMP_RD_UNPACKED_DIR"/sbin/ueventd");
    remove(TMP_RD_UNPACKED_DIR"/sbin/watchdogd");
    symlink("../main_init", TMP_RD_UNPACKED_DIR"/sbin/ueventd");
    symlink("../main_init", TMP_RD_UNPACKED_DIR"/sbin/watchdogd");

#ifdef MR_USE_MROM_FSTAB
    snprintf(buf, sizeof(buf), "%s/mrom.fstab", mrom_dir());
    copy_file(buf, TMP_RD_UNPACKED_DIR"/mrom.fstab");
#else
    remove(TMP_RD_UNPACKED_DIR"/mrom.fstab");
#endif

#ifdef MR_ENCRYPTION
    remove_dir(TMP_RD_UNPACKED_DIR"/mrom_enc");

    if(mr_system("busybox cp -a \"%s/enc\" \"%s/mrom_enc\"", mrom_dir(), TMP_RD_UNPACKED_DIR) != 0)
    {
        ERROR("Failed to copy encryption files!\n");
        return -1;
    }
#endif
    return 0;
}
Exemplo n.º 18
0
bool __connman_storage_remove_service(const char *service_id)
{
	bool removed;

	/* Remove service configuration file */
	removed = remove_file(service_id, SETTINGS);
	if (!removed)
		return false;

	/* Remove the statistics file also */
	removed = remove_file(service_id, "data");
	if (!removed)
		return false;

	removed = remove_dir(service_id);
	if (!removed)
		return false;

	DBG("Removed service dir %s/%s", STORAGEDIR, service_id);

	return true;
}
Exemplo n.º 19
0
/* share code for file and directory deletion, saves space */
static bool delete_file_dir(void)
{
    char file_to_delete[MAX_PATH];
    strcpy(file_to_delete, selected_file);

    const char *lines[]={
        ID2P(LANG_REALLY_DELETE),
        file_to_delete
    };
    const char *yes_lines[]={
        ID2P(LANG_DELETING),
        file_to_delete
    };

    const struct text_message message={lines, 2};
    const struct text_message yes_message={yes_lines, 2};

    if(gui_syncyesno_run(&message, &yes_message, NULL)!=YESNO_YES)
        return false;

    splash(0, str(LANG_DELETING));

    int res;
    if (selected_file_attr & ATTR_DIRECTORY) /* true if directory */
    {
        char pathname[MAX_PATH]; /* space to go deep */
        cpu_boost(true);
        strlcpy(pathname, file_to_delete, sizeof(pathname));
        res = remove_dir(pathname, sizeof(pathname));
        cpu_boost(false);
    }
    else
        res = remove(file_to_delete);

    if (!res)
        onplay_result = ONPLAY_RELOAD_DIR;

    return (res == 0);
}
Exemplo n.º 20
0
gboolean __connman_storage_remove_service(const char *service_id)
{
	gboolean removed;

	/* Remove service configuration file */
	removed = remove_file(service_id, SETTINGS);
	if (removed == FALSE)
		return FALSE;

	/* Remove the statistics file also */
	removed = remove_file(service_id, "data");
	if (removed == FALSE)
		return FALSE;

	removed = remove_dir(service_id);
	if (removed == FALSE)
		return FALSE;

	DBG("Removed service dir %s/%s", STORAGEDIR, service_id);

	return TRUE;
}
Exemplo n.º 21
0
static void __sysfs_remove_dir(struct sysfs_dirent *dir_sd)
{
	struct sysfs_addrm_cxt acxt;
	struct sysfs_dirent **pos;

	if (!dir_sd)
		return;

	pr_debug("sysfs %s: removing dir\n", dir_sd->s_name);
	sysfs_addrm_start(&acxt, dir_sd);
	pos = &dir_sd->s_dir.children;
	while (*pos) {
		struct sysfs_dirent *sd = *pos;

		if (sysfs_type(sd) != SYSFS_DIR)
			sysfs_remove_one(&acxt, sd);
		else
			pos = &(*pos)->s_sibling;
	}
	sysfs_addrm_finish(&acxt);

	remove_dir(dir_sd);
}
Exemplo n.º 22
0
/*
	rm -rf : first empty directory, then remove directory
*/
int rm_rf_trashdir(char *dirname) {
char buf[MAX_PATHLEN], *bufp;
DIR *dirp;
struct dirent *direntp;

	if (dirname == NULL || !*dirname)
		return -1;

/* safety check */
	bufprintf(buf, sizeof(buf), "%s/", PARAM_TRASHDIR);
	path_strip(buf);
	if (strncmp(buf, dirname, strlen(buf)) || cstrstr(dirname, "..") != NULL)
		return -1;

	cstrcpy(buf, dirname, MAX_PATHLEN);
	bufp = buf+strlen(buf)-1;
	if (*bufp != '/') {
		bufp++;
		*bufp = '/';
		bufp++;
		*bufp = 0;
	}
	if ((dirp = opendir(buf)) == NULL)
		return -1;

	while((direntp = readdir(dirp)) != NULL) {
/* check for '.' and '..' directory */
		if (direntp->d_name[0] == '.' && (!direntp->d_name[1]
			|| (direntp->d_name[1] == '.' && !direntp->d_name[2])))
			continue;

		cstrcpy(bufp, direntp->d_name, MAX_PATHLEN);
		unlink(buf);		/* note: trash/ is not cached ; it's ok not to use unlink_file() */
	}
	closedir(dirp);
	return remove_dir(dirname);
}
Exemplo n.º 23
0
Arquivo: rmdir.c Projeto: 8l/FUZIX
int main(int argc, char **argv)
{
    int i, parent = 0, er = 0;

    if ((argv[1][0] == '-') && (argv[1][1] == 'p'))
	parent = 1;

    newmode = 0666 & ~umask(0);

    for (i = parent + 1; i < argc; i++) {
	if (argv[i][0] != '-') {
	    if (remove_dir(argv[i], parent)) {
	        writes("rmdir: cannot remove directory '");
	        writes(argv[i]);
	        perror("'");
		er = 1;
	    }
	} else {
	    writes("rmdir: usage error\n");
	    exit(1);
	}
    }
    return er;
}
Exemplo n.º 24
0
void mkvmerge_wrapper::merge(QString &target_file_name, QDir &resource_dir)
{
    QFile target_file(target_file_name);
    QFileInfo target_file_info(target_file);
    resource_dir.setFilter(QDir::Files | QDir::NoSymLinks);

    QFileInfoList list_of_files = resource_dir.entryInfoList();

    // Assemble merge command
    QString first_segment_name = list_of_files.at(0).absoluteFilePath();
    QString cmd = mkvmerge_cmd_+ mkvmerge_parameters_ + target_file_info.absoluteFilePath() +
            " " + first_segment_name;
    for (int i = 1; i < list_of_files.size(); ++i)
    {
        cmd += " +" + list_of_files.at(i).absoluteFilePath();
    }
    // Run merging
    if (!system(cmd.toStdString().c_str()))
    {
        qDebug() << "mkvmerge call (merge method) caused problem!";
    }
    // Removes folder
    remove_dir(resource_dir);
}
Exemplo n.º 25
0
int main(int argc,char *argv[])
{
  char  infile1[256], infile2[256], infile3[256];  // Input file name                         
  char  outfile[256];         			   // Output file name
  char tmpPath[1024];
  browse_type_t mode = NOTYPE;
  int   i,j;
  int   sample_count;
  double scale;
  extern int currArg;
  strcpy(tmpPath, "");

  // Parse command line
  if ((argc-currArg)<1) {
    printf("Insufficient arguments.\n"); 
    usage("");
  }

  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatches(key, "-sentinel", "--sentinel", NULL)) {
      CHECK_ARG(1);
      scale = atof(GET_ARG(1));
      mode = SENTINEL_DUAL;
    }
    else if (strmatches(key, "-tmpDir", "--tmpDir", NULL)) {
      CHECK_ARG(1);
      strcpy(tmpPath, GET_ARG(1));
    }
    else if (strmatches(key, "-log", "--log", NULL)) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = TRUE;
    }
    else if (strmatches(key, "-quiet", "--quiet", "-q", NULL))
      quietflag = TRUE;
    else {
      --currArg;
      break;
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  if (mode == NOTYPE && argc == 4)
    mode = PALSAR_FBD;
  else if (mode == NOTYPE && argc == 5) 
    mode = PALSAR_PLR;

  if (!quietflag) 
    asfSplashScreen(argc, argv);

  if (mode == PALSAR_FBD) {
  
    asfPrintStatus("Creating colorized browse image from PALSAR FBD data\n");
    create_name(infile1,argv[1],".img");
    create_name(infile2,argv[2],".img");
    create_name(outfile,argv[3],".img");

    meta_parameters *meta1 = meta_read(infile1);
    meta_parameters *meta2 = meta_read(infile2);

    if (meta1->general->line_count != meta2->general->line_count ||
        meta1->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }    
    strcpy(meta1->general->bands,"HH");
    strcpy(meta2->general->bands,"HV");

    int pixel_count = meta1->general->line_count*meta1->general->sample_count;
    float *buf1 = MALLOC(pixel_count * sizeof(float));
    float *buf2 = MALLOC(pixel_count * sizeof(float));
    float *buf3 = MALLOC(pixel_count * sizeof(float));
    unsigned char *cbuf1, *cbuf2, *cbuf3;
    FILE *fp1 = FOPEN(infile1, "r");
    FILE *fp2 = FOPEN(infile2, "r");
    FILE *ofp = FOPEN(outfile, "w");
    char ofile1[256];
    char ofile2[256];

    strcpy(ofile1,argv[1]);
    strcat(ofile1,"_DB.img");
    strcpy(ofile2,argv[2]);
    strcat(ofile2,"_DB.img");
 
    printf("Creating output DB files %s and %s\n",ofile1,ofile2);
    FILE *ofp1 = FOPEN(ofile1, "w");
    FILE *ofp2 = FOPEN(ofile2, "w");

    get_float_lines(fp1,meta1,0,meta1->general->line_count, buf1);
    get_float_lines(fp2,meta2,0,meta2->general->line_count, buf2);

    /* Convert data from sigma0 to dB */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
        if (meta_is_valid_double(buf1[sample_count])) {
          if (buf1[sample_count] != 0)
            buf1[sample_count] = 10.0 * log10f(buf1[sample_count]);
          if (buf2[sample_count] != 0)
            buf2[sample_count] = 10.0 * log10f(buf2[sample_count]);
        }
  	sample_count++;
      }
    }
    put_float_lines(ofp1, meta1, 0,meta1->general->line_count,buf1);
    put_float_lines(ofp2, meta2, 0,meta1->general->line_count,buf2);

    meta_write(meta1, ofile1);
    meta_write(meta2, ofile2);

    fclose(fp1);
    fclose(fp2);
    fclose(ofp1);
    fclose(ofp2);

    /* Scale the data to a byte range using given min/max values */
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,MINMAX,-30.0,-1.0); 
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,MINMAX,-30.0,-10.0); 
   
    /* 
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,MINMAX,-31.0,7.1); 
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,MINMAX,-31.0,7.1);
    */

    strcpy(ofile1,argv[1]);
    strcat(ofile1,"_byte.img");
    strcpy(ofile2,argv[2]);
    strcat(ofile2,"_byte.img");
 
    printf("Creating output byte files %s and %s\n",ofile1,ofile2);
    ofp1 = FOPEN(ofile1, "w");
    ofp2 = FOPEN(ofile2, "w");

    meta1->general->data_type=REAL32;
    meta2->general->data_type=REAL32;

    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf1[sample_count] = (float) cbuf1[sample_count];
          buf2[sample_count] = (float) cbuf2[sample_count];
  	  sample_count++;
      }
    }

    put_float_lines(ofp1,meta1,0,meta1->general->line_count,buf1); 
    put_float_lines(ofp2,meta2,0,meta2->general->line_count,buf2); 

    meta_write(meta1, ofile1);
    meta_write(meta2, ofile2);

    fclose(ofp1);
    fclose(ofp2);

    /* Create the third band for the color image */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
 	 if (buf2[sample_count] != 0) {
           /*
           buf3[sample_count] = (buf1[sample_count] / buf2[sample_count]); 
           */

           buf3[sample_count] = (buf1[sample_count] - buf2[sample_count]);
           if (buf3[sample_count] < 1) buf3[sample_count] = 1;
           else if (buf3[sample_count] > 255) buf3[sample_count] = 255;
         } else buf3[sample_count] = 0;
         sample_count++;
       }
    }

    cbuf3 = my_floats_to_bytes(buf3,(long long) pixel_count, 0.0,SIGMA ,-25.0,-10.0); 
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf3[sample_count] = (float) cbuf3[sample_count];
  	  sample_count++;
      }
    }

    /* Finally, create the 3 banded image we were looking for */
    strcpy(meta1->general->bands,"HH,HV,DIV");
    meta1->general->band_count=3;
    put_band_float_lines(ofp,meta1,0,0,meta1->general->line_count,buf1);
    put_band_float_lines(ofp,meta1,1,0,meta1->general->line_count,buf2);
    put_band_float_lines(ofp,meta1,2,0,meta1->general->line_count,buf3);

    meta_write(meta1,outfile);

  } 
  else if (mode == PALSAR_PLR) {
  
    /* Mode 1 - Create Color Browse from 3 bands using 3sigma stretch */
    asfPrintStatus("Creating colorized browse image from PALSAR PLR data\n");
    create_name(infile1,argv[1],".img");
    create_name(infile2,argv[2],".img");
    create_name(infile3,argv[3],".img");
    create_name(outfile,argv[4],".img");

    meta_parameters *meta1 = meta_read(infile1);
    meta_parameters *meta2 = meta_read(infile2);
    meta_parameters *meta3 = meta_read(infile3);

    if (meta1->general->line_count != meta2->general->line_count ||
        meta1->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }

    if (meta3->general->line_count != meta2->general->line_count ||
        meta3->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }

    int pixel_count = meta1->general->line_count*meta1->general->sample_count;
    float *buf1 = MALLOC(pixel_count * sizeof(float));
    float *buf2 = MALLOC(pixel_count * sizeof(float));
    float *buf3 = MALLOC(pixel_count * sizeof(float));
    float *buf4 = MALLOC(pixel_count * sizeof(float));
    unsigned char *cbuf1, *cbuf2, *cbuf3, *cbuf4;
    FILE *fp1 = FOPEN(infile1, "r");
    FILE *fp2 = FOPEN(infile2, "r");
    FILE *fp3 = FOPEN(infile3, "r");
    FILE *ofp = FOPEN(outfile, "w");

    get_float_lines(fp1,meta1,0,meta1->general->line_count, buf1);
    get_float_lines(fp2,meta2,0,meta2->general->line_count, buf2);
    get_float_lines(fp3,meta3,0,meta3->general->line_count, buf3);

    /* Convert data from sigma0 to dB */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
        if (meta_is_valid_double(buf1[sample_count])) {
          if (buf1[sample_count] != 0)
            buf1[sample_count] = 10.0 * log10f(buf1[sample_count]);
          if (buf2[sample_count] != 0)
            buf2[sample_count] = 10.0 * log10f(buf2[sample_count]);
          if (buf3[sample_count] != 0)
            buf3[sample_count] = 10.0 * log10f(buf3[sample_count]);
        }
  	sample_count++;
      }
    }
    /* Scale the data to a byte range using 3-sigma stretch values */
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,SIGMA3,-30.0,-1.0);
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,SIGMA3,-30.0,-10.0);
    cbuf3 = my_floats_to_bytes(buf3,(long long) pixel_count, 0.0,SIGMA3,-30.0,-10.0);

    meta1->general->data_type=REAL32;
    //meta2->general->data_type=ASF_BYTE;
    //meta3->general->data_type=ASF_BYTE;

    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf1[sample_count] = (float) cbuf1[sample_count];
          buf2[sample_count] = (float) cbuf2[sample_count];
          buf3[sample_count] = (float) cbuf3[sample_count];
          sample_count++;
      }
    }
 
    /* Finally, create the 3 banded image we were looking for */
    strcpy(meta1->general->bands,"HH,HV,VV");
    meta1->general->band_count=3;
    put_band_float_lines(ofp,meta1,0,0,meta1->general->line_count,buf1);
    put_band_float_lines(ofp,meta1,1,0,meta1->general->line_count,buf2);
    put_band_float_lines(ofp,meta1,2,0,meta1->general->line_count,buf3);

    meta_write(meta1,outfile);
  }
  else if (mode == SENTINEL_DUAL) {
  
    asfPrintStatus("Creating colorized browse image from Sentinel dual-pol "
      "data\n");
    if (strlen(tmpPath) > 0) {
      create_name(infile1,argv[5],".img");
      create_name(infile2,argv[6],".img");
      create_name(outfile,argv[7],".tif");
    }
    else {
      create_name(infile1,argv[3],".img");
      create_name(infile2,argv[4],".img");
      create_name(outfile,argv[5],".tif");
    }

    // Create temporary directory
    char tmpDir[1024];
    if (strlen(tmpPath) > 0)
      sprintf(tmpDir, "%s%cbrowse-", tmpPath, DIR_SEPARATOR);
    else
      strcpy(tmpDir, "browse-");
    strcat(tmpDir, time_stamp_dir());
    create_clean_dir(tmpDir);
    asfPrintStatus("Temp dir is: %s\n", tmpDir);
  
    // Calculate ratio image
    char tmpRatio[512], tmpRed[512], tmpGreen[512], tmpBlue[512], tmpIn[512];
    char *inFiles[2]; 
    inFiles[0] = (char *) MALLOC(sizeof(char)*255);
    inFiles[1] = (char *) MALLOC(sizeof(char)*255);
    strcpy(inFiles[0], infile1);
    strcpy(inFiles[1], infile2);
    sprintf(tmpRatio, "%s%cdiv.img", tmpDir, DIR_SEPARATOR);
    raster_calc(tmpRatio, "a/b", 2, inFiles);
    
    // Resample all three bands and scale to byte
    meta_parameters *metaIn = meta_read(tmpRatio);
    double scaleFactor = 1.0/(scale/metaIn->general->x_pixel_size);
    meta_free(metaIn);
    sprintf(tmpIn, "%s%cred.img", tmpDir, DIR_SEPARATOR);
    resample(infile1, tmpIn, scaleFactor, scaleFactor);
    sprintf(tmpRed, "%s%cred_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpRed, NULL, -40.0, SIGMA);
    sprintf(tmpIn, "%s%cgreen.img", tmpDir, DIR_SEPARATOR);
    resample(infile2, tmpIn, scaleFactor, scaleFactor);
    sprintf(tmpGreen, "%s%cgreen_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpGreen, NULL, -40.0, SIGMA);
    sprintf(tmpIn, "%s%cblue.img", tmpDir, DIR_SEPARATOR);
    resample(tmpRatio, tmpIn, scaleFactor, scaleFactor);    
    sprintf(tmpBlue, "%s%cblue_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpBlue, NULL, -40.0, SIGMA);

    // Layer stack the bands
    char tmpBrowse[512];
    sprintf(tmpBrowse, "%s%cbrowse.img", tmpDir, DIR_SEPARATOR);
    FILE *fpOut = FOPEN(tmpBrowse, "w");    
    meta_parameters *metaOut = meta_read(tmpRed);
    metaOut->general->band_count = 3;
    metaIn = meta_read(tmpRed);
    int line_count = metaIn->general->line_count;
    int sample_count = metaIn->general->sample_count;
    
    float *buf = (float *) MALLOC(sizeof(float)*line_count*sample_count);
    FILE *fpIn = FOPEN(tmpBlue, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 0, 0, line_count, buf);
    FCLOSE(fpIn);
    fpIn = FOPEN(tmpGreen, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 1, 0, line_count, buf);
    FCLOSE(fpIn);
    fpIn = FOPEN(tmpRed, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 2, 0, line_count, buf);
    FCLOSE(fpIn);
    FCLOSE(fpOut);
    FREE(buf);

    strcpy(metaOut->general->bands, "red,green,blue");
    meta_write(metaOut, tmpBrowse);
    
    // Export to GeoTIFF
    char *band_names[3] = { "blue", "green", "red" };
    asf_export_bands(GEOTIFF, NONE, TRUE, FALSE, FALSE, FALSE, FALSE, 
      tmpBrowse, outfile, band_names, NULL, NULL);

    // Clean up
    asfPrintStatus("Removing temporary directory: %s\n", tmpDir);
    remove_dir(tmpDir);
    meta_free(metaIn);
    meta_free(metaOut);
  }
  else
    asfPrintError("Mode is not defined!\n");

  asfPrintStatus("Done.\n");
  exit(EXIT_SUCCESS);
}
Exemplo n.º 26
0
void doit(void)
{
    int child;
    int children_left;

    child_status = (int *)mmap(	0,
                                n_threads * sizeof(*child_status),
                                PROT_READ|PROT_WRITE,
                                MAP_SHARED|MAP_ANONYMOUS,
                                -1,
                                0);
    if (child_status == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }

    memset(child_status, 0, n_threads * sizeof(*child_status));

    thread_group = -1;
    for (this_child_index = 0;
            this_child_index < n_threads; this_child_index++)
    {
        if (this_child_index % threads_per_dir == 0) {
            thread_group++;
            make_dir();
        }

        if (fork() == 0) {
            int iter;

            for (iter = 0; iter < n_iters; iter++)
                do_child();
            child_status[this_child_index] = 1;
            exit(0);
        }
    }

    /* Parent */
    children_left = n_threads;
    while (children_left) {
        int status;

        if( wait3(&status, 0, 0) < 0 ) {
            if( errno != EINTR ) {
                perror("wait3");
                exit(1);
            }
            continue;
        }
        for (child = 0; child < n_threads; child++) {
            if (child_status[child] == 1) {
                child_status[child] = 2;
                printf("*");
                fflush(stdout);
                children_left--;
            }
        }
    }
    for (thread_group = 0;
            thread_group < ( n_threads / threads_per_dir );
            thread_group++ )
        remove_dir();

    printf("\n");
}
Exemplo n.º 27
0
int test_c2v(char *inFile, const char *inFormat_str,
	     char *outFile, const char *outFormat_str)
{
  int ret = 0;
  int listFlag = 0;
  format_type_t inFormat = str2format(inFormat_str);
  format_type_t outFormat = str2format(outFormat_str);
  char *tmpFile = (char *) MALLOC(sizeof(char)*255);
  char *tmpDir = (char *) MALLOC(sizeof(char)*512);

  // Convert the formats forth and back, otherwise back out
  if (inFormat == POINT && outFormat == KMLFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/point.kml", tmpDir);
    ret = point2kml(inFile, tmpFile, listFlag);
    if (ret)
      ret = kml2point(tmpFile, outFile, listFlag);
  }
  else if (inFormat == POINT && outFormat == SHAPEFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/point", tmpDir);
    ret = point2shape(inFile, tmpFile, listFlag);
    if (ret)
      ret = shape2point(tmpFile, outFile, listFlag);
  }
  else if (inFormat == POLYGON && outFormat == KMLFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/polygon.kml", tmpDir);
    ret = polygon2kml(inFile, tmpFile, listFlag);
    if (ret)
      ret = kml2polygon(tmpFile, outFile, listFlag);
  }
  else if (inFormat == POLYGON && outFormat == SHAPEFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/polygon", tmpDir);
    ret = polygon2shape(inFile, tmpFile, listFlag);
    if (ret)
      ret = shape2polygon(tmpFile, outFile, listFlag);
  }
  else if (inFormat == CSV && outFormat == KMLFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/csv.kml", tmpDir);
    ret = csv2kml(inFile, tmpFile, listFlag);
    if (ret)
      ret = kml2csv(tmpFile, outFile, listFlag);
  }
  else if (inFormat == CSV && outFormat == SHAPEFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/csv", tmpDir);
    ret = csv2shape(inFile, tmpFile, listFlag);
    if (ret)
      ret = shape2csv(tmpFile, outFile, listFlag);
  }
  else if (inFormat == AUIG && outFormat == KMLFILE) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/auig.kml", tmpDir);
    ret = auig2kml(inFile, tmpFile, listFlag);
    if (ret)
      ret = kml2auig(tmpFile, outFile, listFlag);
  }
  else if (inFormat == KMLFILE && outFormat == POINT) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/point.csv", tmpDir);
    ret = kml2point(inFile, tmpFile, listFlag);
    if (ret)
      ret = point2kml(tmpFile, outFile, listFlag);
  }
  else if (inFormat == KMLFILE && outFormat == POLYGON) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/polygon.csv", tmpDir);
    ret = kml2polygon(inFile, tmpFile, listFlag);
    if (ret)
      ret = polygon2kml(tmpFile, outFile, listFlag);
  }
  else if (inFormat == KMLFILE && outFormat == CSV) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/generic.csv", tmpDir);
    ret = kml2csv(inFile, tmpFile, listFlag);
    if (ret)
      ret = csv2kml(tmpFile, outFile, listFlag);
  }
  else if (inFormat == KMLFILE && outFormat == AUIG) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/auig.csv", tmpDir);
    ret = kml2auig(inFile, tmpFile, listFlag);
    if (ret)
      ret = auig2kml(tmpFile, outFile, listFlag);
  }
  else if (inFormat == SHAPEFILE && outFormat == POINT) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/point.csv", tmpDir);
    ret = shape2point(inFile, tmpFile, listFlag);
    if (ret)
      ret = point2shape(tmpFile, outFile, listFlag);
  }
  else if (inFormat == SHAPEFILE && outFormat == POLYGON) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/polygon.csv", tmpDir);
    ret = shape2polygon(inFile, tmpFile, listFlag);
    if (ret)
      ret = polygon2shape(tmpFile, outFile, listFlag);
  }
  else if (inFormat == SHAPEFILE && outFormat == CSV) {
    setup_test_dir(tmpDir);
    sprintf(tmpFile, "%s/generic.csv", tmpDir);
    ret = shape2csv(inFile, tmpFile, listFlag);
    if (ret)
      ret = csv2shape(tmpFile, outFile, listFlag);
  }
  else
    asfPrintError("Conversion irreversible. Can't perform test\n");

  // Clean up
  remove_dir(tmpDir);
  FREE(tmpFile);
  FREE(tmpDir);

  return ret;
}
Exemplo n.º 28
0
/* Paste the clipboard to the current directory */
static bool clipboard_paste(void)
{
    char target[MAX_PATH];
    char *cwd, *nameptr;
    bool success;

    static const char *lines[]={ID2P(LANG_REALLY_OVERWRITE)};
    static const struct text_message message={lines, 1};

    /* Get the name of the current directory */
    cwd = getcwd(NULL, 0);

    /* Figure out the name of the selection */
    nameptr = strrchr(clipboard_selection, '/');

    /* Final target is current directory plus name of selection  */
    snprintf(target, sizeof(target), "%s%s", cwd[1] ? cwd : "", nameptr);

    /* If the target existed but they choose not to overwite, exit */
    if (file_exists(target) &&
        (gui_syncyesno_run(&message, NULL, NULL) == YESNO_NO)) {
        return false;
    }

    if (clipboard_is_copy) {
        splash(0, ID2P(LANG_COPYING));
    }
    else
    {
        splash(0, ID2P(LANG_MOVING));
    }

    /* Now figure out what we're doing */
    cpu_boost(true);
    if (clipboard_selection_attr & ATTR_DIRECTORY) {
        /* Recursion. Set up external stack */
        char srcpath[MAX_PATH];
        char targetpath[MAX_PATH];
        if (!strncmp(clipboard_selection, target, strlen(clipboard_selection)))
        {
            /* Do not allow the user to paste a directory into a dir they are
               copying */
            success = 0;
        }
        else
        {
            strlcpy(srcpath, clipboard_selection, sizeof(srcpath));
            strlcpy(targetpath, target, sizeof(targetpath));

            success = clipboard_pastedirectory(srcpath, sizeof(srcpath),
                             target, sizeof(targetpath), clipboard_is_copy);

            if (success && !clipboard_is_copy)
            {
                strlcpy(srcpath, clipboard_selection, sizeof(srcpath));
                remove_dir(srcpath, sizeof(srcpath));
            }
        }
    } else {
        success = clipboard_pastefile(clipboard_selection, target,
            clipboard_is_copy);
    }
    cpu_boost(false);

    /* Did it work? */
    if (success) {
        /* Reset everything */
        clipboard_selection[0] = 0;
        clipboard_selection_attr = 0;
        clipboard_is_copy = false;

        /* Force reload of the current directory */
        onplay_result = ONPLAY_RELOAD_DIR;
    } else {
        cond_talk_ids_fq(LANG_PASTE, LANG_FAILED);
        splashf(HZ, (unsigned char *)"%s %s", str(LANG_PASTE),
                                              str(LANG_FAILED));
    }

    return true;
}
Exemplo n.º 29
0
/* Paste a directory to a new location. Designed to be called by
   clipboard_paste */
static bool clipboard_pastedirectory(char *src, int srclen, char *target,
                                     int targetlen, bool copy)
{
    DIR *srcdir;
    int srcdirlen = strlen(src);
    int targetdirlen = strlen(target);
    bool result = true;

    if (!file_exists(target)) {
        if (!copy) {
            /* Just move the directory */
            result = rename(src, target) == 0;

#ifdef HAVE_MULTIVOLUME
            if (!result && errno == EXDEV) {
                /* Try a copy as we're going across devices */
                result = clipboard_pastedirectory(src, srclen, target,
                    targetlen, true);

                /* If it worked, remove the source directory */
                if (result) {
                    remove_dir(src, srclen);
                }
            }
#endif
            return result;
        } else {
            /* Make a directory to copy things to */
            result = mkdir(target) == 0;
        }
    }

    /* Check if something went wrong already */
    if (!result) {
        return result;
    }

    srcdir = opendir(src);
    if (!srcdir) {
        return false;
    }

    /* This loop will exit as soon as there's a problem */
    while(result)
    {
        struct dirent* entry;
        /* walk through the directory content */
        entry = readdir(srcdir);
        if (!entry)
            break;

        struct dirinfo info = dir_get_info(srcdir, entry);
        /* append name to current directory */
        snprintf(src+srcdirlen, srclen-srcdirlen, "/%s", entry->d_name);
        snprintf(target+targetdirlen, targetlen-targetdirlen, "/%s",
            entry->d_name);

        DEBUGF("Copy %s to %s\n", src, target);

        if (info.attribute & ATTR_DIRECTORY)
        {   /* copy/move a subdirectory */
            if (!strcmp((char *)entry->d_name, ".") ||
                !strcmp((char *)entry->d_name, ".."))
                continue; /* skip these */

            result = clipboard_pastedirectory(src, srclen, target, targetlen,
                copy); /* recursion */
        }
        else
        {   /* copy/move a file */
            draw_slider();
            result = clipboard_pastefile(src, target, copy);
        }
    }

    closedir(srcdir);

    if (result) {
        src[srcdirlen] = '\0'; /* terminate to original length */
        target[targetdirlen] = '\0'; /* terminate to original length */
    }

    return result;
}
Exemplo n.º 30
0
/* argc, *argv[] assume usual meaning */
int main(int argc, char *argv[])
{
	char buf[BUFSIZE+1];	/* temporary buffer for storing the line input */
	char pwd[BUFSIZE+1];	/* stores the present working directory */
	char errstr[BUFSIZE+1];	/* stores the error occured */
	char *tok[ARGNUM];	/* for storing the tokens */	
	int n, i;	/* n will store the no. of tokens starting from 0 */
	int returnval;	/* used by wait() */
	
//	n = ARGNUM-1;

	signal(SIGINT, SIG_IGN);
	signal(SIGINT, ignore_line); /* ignore current line on Ctrl-C */
	
	while (1)
	{
		/* very important: */
		/* reset the state to -1 */
		state = -1;
		/* reset the token array */
		for (i = 0; i <= n; i++)
			tok[i] = "\0";
		/* reset the buffer */
		for (i = 0; i <= BUFSIZE; i++)
			buf[i] = '\0';

		/* print the prompt with the pwd */
		set_prompt();
		/* read input from STDIN */
		read(STDIN_FILENO, buf, BUFSIZE);
		#ifdef DEBUG
		{
			fprintf(stderr, "buf: %s", buf);	/* no newline is given because buf includes newline from read() */
		}
		#endif

		/* extract the first token (the command)*/
		tok[0] = strtok(buf, DELIMS);		
		
		n = 1;

		/* extract the remaining tokens */
		while ((tok[n] = strtok(NULL, DELIMS)) != NULL) /* sending NULL in subsequent strtok calls will return the remaining tokens */
			n++;
		
		tok[n] = NULL;	/* very importatnt to set the last token as NULL, for specifying the end of tokens */
	
		n--;	/* remove the extra 1 that is added to n */
		
		/* if debug mode is on, print all tokens */	
		#ifdef DEBUG
		{
			i = 0;
			fprintf(stderr, "tokenizing buf\n");
			fprintf(stderr, "n: %d\n", n);
			while (i <= n)
			{
				fprintf(stderr, "tok[%d]: %s\n", i, tok[i]);
				i++;
			}
			fprintf(stderr, "looking up on token: %s\n", tok[0]);
		}
		#endif

		/* lookup on the first token */
		for (i = _EXIT; i < CMDNUM; i++)
			if (strcmp(tok[0], cmd[i]) == 0)
				state = i;	/* set the state to its command equivalent */

		/* switch to a state (execute a command) based on the token */
		switch (state)
		{
			case _EXIT:
				return 0;

			case _SYS:
				switch (fork())	/* is this the child process? */
				{	
					case 0:
						returnval = execvp(tok[1], &tok[1]);	/* tok[1] because tok[0] would contain sys */
						exit(returnval);	/* child always exits with 200 on success */
					default:
						wait(&returnval);
				}
				/* wait till the first child process dies */
				wait(&returnval);
				break;

			case _LS:
				list_dir(n, tok);
				break;
	
			case _ECHO:
				for(i = 1; i <= n; i++)
					fprintf(stdout, "%s ", tok[i]);
				fprintf(stdout, "\n");
				break;

			case _PWD:
				getcwd(pwd, BUFSIZE);
				fprintf(stdout, "%s\n", pwd); 
				break;

			case _CLEAR:
				system(tok[0]);
				break;

			case _CD:
				/* if no argument is given, change to home directory */
				if (n == 0)
					if (chdir((char *)getenv("HOME")) == -1)
						perror("cd");
				else 
				{	if (chdir(tok[1]) == -1)
						perror("cd");}
				break;

			case _CAT:
				cat(n, tok);
				break;

			case _MKDIR:
				create_dir(n, tok);
				break;
			
			case _RMDIR:
				remove_dir(n, tok);
				break;

			case _HELP:
				/* print a list of commands with basic usage help */
				fprintf(stdout, "You are running Dhanu-sh\nType 'help (command)' for more details\n");
				if (n == 0)
				{
					fprintf(stdout, "The following commands are available:\n");
					for (i = 0; i < CMDNUM; i++)
						fprintf(stdout, " %s\n", cmd[i]);
				}
				else
				{
					for (i = 0; i < CMDNUM; i++)
						if (strcmp(cmd[i], tok[1]) == 0)
							fprintf(stdout, " %s usage: %s\n%s    \n", cmd[i], usage[i], desc[i]);
				}
				break;

			case _RM:
				remove_file(n, tok);
				break;
				
			case _CHROOT:
				change_root(n, tok);
				break;
	
			case _MV:
				move(n, tok);
				break;
	
			case _CP:
				copy_file(n, tok);
				break;	

			default:
				switch (fork())
				{
					case 0:
						returnval = execvp(tok[0], &tok[0]);
						fprintf(stderr, "%s: No such file or directory\n", tok[0]);
						exit(returnval);
					default:
						wait(&returnval);
				}
		}
	}
	return 0;
}