/** * Remove files from directory * * @param path Directory path * * @return 0 on success, negative value in case of an error */ int remove_dir_content(const char *path) { file_info *file_list = 0, *dir_list = 0; int ret = -1; ret = generate_file_list(path, &file_list, &dir_list); if (ret < 0) { LOGE("generate_file_list for %s failed\n", path); goto err; } ret = delete_files(&file_list); if (ret < 0) { LOGE("delete_files %s failed\n", path); goto err; } ret = delete_files(&dir_list); if (ret < 0) { LOGE("delete dirs failed %s\n", path); goto err; } free_list(&file_list); free_list(&dir_list); return 0; err: free_list(&file_list); free_list(&dir_list); return ret; }
t_file *store_files(char *dirname, DIR *dirp, t_command *command) { t_file *files; struct stat *fileinfo; char *fullname; struct dirent *dir; files = NULL; fileinfo = NULL; while ((dir = readdir(dirp))) { if (!has_option(command->options, 'a') && dir->d_name[0] == '.') continue ; if (!(fullname = ft_strjoin(ft_strjoin(dirname, "/"), dir->d_name))) return (delete_files(&files)); if (!(fileinfo = malloc(sizeof(*fileinfo)))) return (delete_variables(&fileinfo, &fullname)); if (lstat(fullname, fileinfo) == -1) { no_such_file_or_directory(fullname); delete_variables(&fileinfo, &fullname); continue ; } add_file_last(&files, new_file(dir->d_name, fileinfo)); ft_strdel(&fullname); } set_file_order(files, command->options); return (files); }
// recurse to delete path(maybe dir or file) void delete_files(const char *path) { DIR *dir; struct dirent *dir_info; char file_path[PATH_MAX]; if (is_file(path)) { remove(path); printf("delete file %s\n", path); return; } if (is_dir(path)) { if ((dir = opendir(path)) == NULL) return; while ((dir_info = readdir(dir)) != NULL) { get_file_path(path, dir_info->d_name, file_path); if (is_special_dir(dir_info->d_name)) continue; delete_files(file_path); rmdir(file_path); } } printf("delete dir %s\n", path); }
int main(int argc, char **argv) { #if 0 delete_files("./dd"); delete_appendix("./aa", ".c"); #endif int n = scan_dir(".", filter); printf("count of *.c files: %d\n", n); return 0; }
/* * destroy function */ static void mod_exit(void) { int i; /* free file containers */ delete_files(&allow, allow_rules_num); delete_files(&deny, deny_rules_num); clean_trusted(); clean_ipmatch(); if (ip_set_list_local) { for (i=0; i<ip_set_list_count; i++) { /* we need delete all cloned sets because might not exist in global list after commit, they have refcnt>1 */ if (ip_set_list_local[i]) shm_free(ip_set_list_local[i]); } } ip_set_list_free(); }
static void test_single_file(CuTest* tc) { char data[] = {0, 1, 10, 100}; int i = 0, data_size = 4; unsigned int size = 0; apr_pool_t *pool; apr_pool_create( &pool, NULL ); for(i = 0; i < data_size; i++ ) { lcn_directory_t *dir; char *seq_file = "seq_file"; LCN_TEST( lcn_fs_directory_create( &dir, dir_test, LCN_TRUE, pool ) ); LCN_TEST( create_sequence_file(dir, seq_file, 0, data[i], pool ) ); // add seq_file to cf writer. lcn_compound_file_writer_t *cfw; LCN_TEST( lcn_compound_file_writer_create( &cfw, dir, cf_name, pool ) ); LCN_TEST( lcn_compound_file_writer_add_file( cfw, seq_file ) ); LCN_TEST( lcn_compound_file_writer_add_file( cfw, seq_file ) ); size = lcn_compound_file_writer_entries_size( cfw ); CuAssertIntEquals(tc, 1, size ); LCN_TEST( lcn_compound_file_writer_close( cfw ) ); lcn_compound_file_reader_t *cfr = NULL; LCN_TEST( lcn_compound_file_reader_create( &cfr, dir, cf_name, pool ) ); size = lcn_compound_file_reader_entries_size ( cfr ); CuAssertIntEquals( tc, 1, size ); lcn_index_input_t *expected = NULL; lcn_index_input_t *actual = NULL; LCN_TEST( lcn_directory_open_input( dir, &expected, seq_file, LCN_IO_CONTEXT_READONCE, pool ) ); LCN_TEST( lcn_compound_file_reader_open_input( cfr, &actual, seq_file ) ); assert_same_stream ( tc, expected, actual ); assert_same_seek_behavior ( tc, expected, actual ); LCN_TEST ( lcn_index_input_close( expected ) ); LCN_TEST ( lcn_index_input_close( actual ) ); LCN_TEST ( lcn_compound_file_reader_close ( cfr ) ); CuAssertTrue ( tc, lcn_compound_file_reader_is_open ( cfr ) == LCN_FALSE ); delete_files( tc, dir_test ); } }
static void test_two_files ( CuTest* tc ) { lcn_directory_t *dir; apr_pool_t *pool; apr_pool_create( &pool, NULL ); LCN_TEST( lcn_fs_directory_create( &dir, dir_test, LCN_TRUE, pool ) ); LCN_TEST( create_sequence_file(dir, "seq_file1", 0, 15, pool ) ); LCN_TEST( create_sequence_file(dir, "seq_file2", 0, 114, pool ) ); lcn_compound_file_writer_t *cfw; LCN_TEST( lcn_compound_file_writer_create( &cfw, dir, "test_two_files.csf", pool ) ); LCN_TEST( lcn_compound_file_writer_add_file( cfw, "seq_file1" ) ); LCN_TEST( lcn_compound_file_writer_add_file( cfw, "seq_file2" ) ); LCN_TEST( lcn_compound_file_writer_close( cfw ) ); lcn_compound_file_reader_t *cfr; LCN_TEST( lcn_compound_file_reader_create( &cfr, dir, "test_two_files.csf", pool ) ); /** * Open seq_file1 and test it. */ lcn_index_input_t *expected = NULL; lcn_index_input_t *actual = NULL; LCN_TEST( lcn_directory_open_input( dir, &expected, "seq_file1", LCN_IO_CONTEXT_READONCE, pool ) ); LCN_TEST( lcn_compound_file_reader_open_input( cfr, &actual, "seq_file1" ) ); assert_same_stream ( tc, expected, actual); assert_same_seek_behavior ( tc, expected, actual ); LCN_TEST ( lcn_index_input_close( expected ) ); LCN_TEST ( lcn_index_input_close( actual ) ); /** * Open seq_file2 and test it. */ LCN_TEST( lcn_directory_open_input( dir, &expected, "seq_file2", LCN_IO_CONTEXT_READONCE, pool ) ); LCN_TEST( lcn_compound_file_reader_open_input( cfr, &actual, "seq_file2" ) ); assert_same_stream ( tc, expected, actual); assert_same_seek_behavior ( tc, expected, actual ); LCN_TEST ( lcn_index_input_close( expected ) ); LCN_TEST ( lcn_index_input_close( actual ) ); LCN_TEST ( lcn_compound_file_reader_close ( cfr ) ); delete_files( tc, dir_test ); }
void sort(const SortParameters& parameters) { std::uint32_t chunk_no = split_into_chunks(parameters.input_filename, parameters.chunk_size); const std::uint32_t initial_chunks_count = chunk_no; std::cout << "Split into " << initial_chunks_count << " chunks." << std::endl; ThreadPool pool(parameters.threads_count); std::vector<std::future<bool>> schedule; // Add tasks for sorting initial chunks for (std::uint32_t i = 0; i < initial_chunks_count; ++i) { schedule.emplace_back(pool.enqueue( [i, ¶meters]() { sort_chunk(get_chunk_filename(i), parameters.chunk_size); std::cout << "Chunk #" << i << " sorted" << std::endl; return true; } )); } // Add tasks for merging chunks for (std::uint32_t i = 0; i * (parameters.no_of_ways_for_merging - 1) + 1 < initial_chunks_count; ++i) { schedule.emplace_back(pool.enqueue( [i, chunk_no, &schedule, ¶meters]() mutable { std::cout << "Merging ["; std::vector<std::string> chunk_filenames; for (std::uint32_t delta = 0; delta < parameters.no_of_ways_for_merging; ++delta) { std::uint32_t needed_chunk_no = parameters.no_of_ways_for_merging * i + delta; if (needed_chunk_no + 1 < schedule.size()) { schedule[needed_chunk_no].wait(); chunk_filenames.emplace_back(get_chunk_filename(needed_chunk_no)); std::cout << needed_chunk_no << " "; } } std::cout << "] into " << chunk_no << std::endl; merge_sorted_chunks(chunk_filenames, get_chunk_filename(chunk_no)); delete_files(chunk_filenames); return true; } )); ++chunk_no; } schedule.back().get(); if (std::rename(get_chunk_filename(chunk_no - 1).c_str(), parameters.output_filename.c_str()) != 0) { throw std::runtime_error("Cannot rename last chunk into output file"); } }
void delete_files(std::string const& old, std::string const& new_) { for ( fs::directory_iterator current_dir(old.c_str()); *current_dir; ++current_dir ) { std::string const entry_name( *current_dir ); std::string const entry( old + '/' + entry_name ); std::string const new_entry( new_ + '/' + entry_name ); if(fs::extension(entry_name) == ".hpp" && !fs::exists(new_entry.c_str())) { fs::remove(entry.c_str()); } if(fs::is_directory(entry)) delete_files(entry, new_entry); } }
int main(int argc, char* argv[]) { if(argc != 3) { std::cout << "usage: " << argv[0] << " <new> <old>" << std::endl; return EXIT_FAILURE; } if(fs::exists(argv[2])) delete_files(argv[2], argv[1]); if(fs::exists(argv[1])) { move_files(argv[2], argv[1]); fs::remove_all(argv[1]); } }
void cb_ctx_delete(GtkWidget *widget, GdkEvent *event) { int count; int button; GEList *files; count = gtk_tree_selection_count_selected_rows(gtk_tree_view_get_selection(tv_files)); if (count == 0) return; button = message_box(w_main, _("Delete selected files"), _("This will delete the selected files from disk. Proceed?"), GTK_BUTTONS_YES_NO, 0); if (button == GTK_RESPONSE_NO) return; files = fl_get_selected_files(); delete_files(files); g_elist_free(files); }
void libre_impuesto_file_helpers_shutdown (void) { g_hash_table_destroy (files); del_on_exit = g_list_reverse (del_on_exit); delete_files (del_on_exit); g_list_foreach (del_on_exit, (GFunc)g_free, NULL); g_list_free (del_on_exit); del_on_exit = NULL; if (mime_table != NULL) { g_hash_table_destroy (mime_table); mime_table = NULL; } g_free (dot_dir); dot_dir = NULL; if (tmp_dir != NULL) { if (!keep_temp_directory) { GFile *tmp_dir_file; tmp_dir_file = g_file_new_for_path (tmp_dir); /* recursively delete the contents and the * directory */ libre_impuesto_file_delete_dir_recursively (tmp_dir_file, NULL); g_object_unref (tmp_dir_file); } g_free (tmp_dir); tmp_dir = NULL; } }
samrpc_result_t * samrpc_delete_files_6_svr( strlst_arg_t *arg, /* argument to api */ struct svc_req *req /* ARGSUSED */ ) { int ret = -1; Trace(TR_DEBUG, "Delete files"); /* free previous result */ xdr_free(xdr_samrpc_result_t, (char *)&rpc_result); SAMRPC_CHECK_TIMESTAMP(arg->ctx->handle->timestamp); Trace(TR_DEBUG, "Calling native library to delete files"); ret = delete_files(arg->ctx, arg->lst); SAMRPC_SET_RESULT(ret, SAM_VOID, 0); Trace(TR_DEBUG, "Delete files return[%d]", ret); return (&rpc_result); }
int read_files(t_file *files, char *dirname, t_waiting **waiting, t_command *command) { t_file *tmp; t_column *clength; tmp = files; if (!(clength = set_columns_length(files, command, 0))) return (0); while (tmp) { if (!read_file(tmp, command, dirname, clength)) { delete_waiting(waiting); delete_files(&files); return (-1); } push_waiting(&tmp, dirname, waiting, command); tmp = tmp->next; } ft_memdel((void**)&clength); return (1); }
int main (int argc, char **argv) { /* Program requires >= 4 arguments */ if(argc < 3) usage(stderr, argv[0], "Insufficient arguments", 1); /* Variable to hold flag currently * being ready by getopt() */ int c; int operation_alters_arch = 0; unsigned int timeout = 0; /* Struct for use with GNU getopt_long() */ struct option longopts[] = { { "quick", no_argument, 0, 'q' }, { "extract", no_argument, 0, 'x' }, { "contents", no_argument, 0, 't' }, { "verbose", no_argument, 0, 'v' }, { "delete", no_argument, 0, 'd' }, { "append", no_argument, 0, 'A' }, { "when", required_argument, 0, 'w' }, { 0, 0, 0, 0 } }; int opt_index = 0; /* * Loop adapted from example given at * http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html * * Loop through command line arguments, incrementing * 'seen' when we encounter a mandatory argument. * * All options besides '-v' require an argument. */ while((c = getopt_long(argc, argv, "qxtvdAw:", longopts, &opt_index)) != -1) { switch(c) { case 'q': case 'x': case 't': case 'v': case 'd': case 'A': case 'w': if(operation != none) { fprintf(stderr, "two different operation options specified\n"); exit(EXIT_FAILURE); } break; } switch(c) { case 'q': operation_alters_arch = 1; operation = append; break; case 'x': operation = extract; break; case 't': operation = contents; break; case 'v': operation = verbose; break; case 'd': operation_alters_arch = 1; operation = delete; break; case 'A': operation_alters_arch = 1; operation = append_all; break; case 'w': operation_alters_arch = 1; operation = append_all; timeout = strtoul(optarg, 0, 10); break; case('?'): default: usage(stderr, argv[0], "unrecognized option", 1); break; } } /* Print usage and exit if no operation * was given */ if(operation == none) usage(stderr, argv[0], "'none' operation specified", 1); /* Array for remaining arguments. * Assumes remaining arguments * are filepaths. */ int count = argc - optind - 1; char *archname = argv[optind++]; if(archname == NULL) usage(stderr, argv[0], "no archive file specified", 1); int arch; /* Temporarily set umask to 0000 in order to * create file with permissions 0666 using * DFLTMODE */ umask(0000); if((operation == append || operation == append_all) && access(archname, R_OK | W_OK) == -1) { printf("%s: creating %s\n", argv[0], archname); arch = open(archname, O_CREAT | O_RDWR, DFLTMODE); } else { arch = open(archname, O_RDWR, DFLTMODE); } umask(DFLTUMASK); if(arch == -1) { fprintf(stderr, "error opening archive\n"); perror("open"); exit(EXIT_FAILURE); } if(isempty(archname)) write_armag(arch); char *files[count]; int i; for(i = 0; optind < argc; i++, optind++) files[i] = argv[optind]; switch(operation) { case append: append_files(arch, archname, files, count); break; case append_all: if(count != 0 && timeout == 0) usage(stderr, argv[0], "-A option takes no arguments", 1); else if(count != 0) usage(stderr, argv[0], "-w option takes no arguments", 1); append_all_files(arch, archname, timeout, &is_reg_file); break; case extract: extract_files(arch, files, count); break; case contents: map_over_members(arch, &print_member_concise, files, count, -1); break; case verbose: map_over_members(arch, &print_member_verbose, files, count, -1); break; case delete: delete_files(arch, archname, files, count); break; case none: default: usage(stderr, argv[0], "no operation option specified", 1); } if(operation_alters_arch != 1) { if(close(arch) == -1) { fprintf(stderr, "failed to close archive %s\n", archname); perror("close"); exit(EXIT_FAILURE); } } return 0; }
void bios_select(int flag) { int sel = 0, rows = 13, top = 0; int i, prev_sel, update = 1; int old_bios = neogeo_bios; if (!bios_check(flag)) return; if (neogeo_bios == -1) { sel = 0; while (sel < BIOS_MAX) { if (bios_exist[sel]) break; sel++; } } else sel = neogeo_bios; if (top > BIOS_MAX - rows) top = BIOS_MAX - rows; if (top < 0) top = 0; if (sel >= BIOS_MAX) sel = 0; if (sel < 0) sel = BIOS_MAX - 1; if (sel >= top + rows) top = sel - rows + 1; if (sel < top) top = sel; pad_wait_clear(); load_background(BG_DEFAULT); ui_popup_reset(); while (1) { if (update) { int width = uifont_get_string_width(TEXT(SELECT_BIOS_AND_PRESS_CIRCLE_BUTTON)); show_background(); small_icon(8, 3, UI_COLOR(UI_PAL_TITLE), ICON_SYSTEM); uifont_print(36, 5, UI_COLOR(UI_PAL_TITLE), TEXT(BIOS_SELECT_MENU)); uifont_print(477 - width, 271 - 16, UI_COLOR(UI_PAL_SELECT), TEXT(SELECT_BIOS_AND_PRESS_CIRCLE_BUTTON)); if (sel != 0) uifont_print(118, 24, UI_COLOR(UI_PAL_SELECT), FONT_UPTRIANGLE); for (i = 0; i < rows; i++) { if (top + i >= BIOS_MAX) break; if (top + i == sel) { uifont_print(12, 40 + i * 17, UI_COLOR(UI_PAL_SELECT), FONT_RIGHTTRIANGLE); uifont_print(32, 40 + i * 17, UI_COLOR(UI_PAL_SELECT), bios_name[top + i]); } else { if (bios_exist[top + i]) uifont_print(32, 40 + i * 17, UI_COLOR(UI_PAL_NORMAL), bios_name[top + i]); else uifont_print(32, 40 + i * 17, COLOR_DARKGRAY, bios_name[top + i]); } } if (sel + rows < BIOS_MAX) uifont_print(118, 260, UI_COLOR(UI_PAL_SELECT), FONT_DOWNTRIANGLE); update = draw_battery_status(1); update |= ui_show_popup(1); video_flip_screen(1); } else { update = draw_battery_status(0); update |= ui_show_popup(0); video_wait_vsync(); } prev_sel = sel; if (pad_pressed(PSP_CTRL_UP)) { if (sel > 0) { if (bios_exist[sel - 1]) { sel--; } else { for (i = sel - 2; i >= 0; i--) if (bios_exist[i]) break; if (i != -1) sel = i; } } } else if (pad_pressed(PSP_CTRL_DOWN)) { if (sel < BIOS_MAX - 1) { if (bios_exist[sel + 1]) { sel++; } else { for (i = sel + 2; i < BIOS_MAX; i++) if (bios_exist[i]) break; if (i != BIOS_MAX) sel = i; } } } else if (pad_pressed(PSP_CTRL_CIRCLE)) { neogeo_bios = sel; break; } if (top > BIOS_MAX - rows) top = BIOS_MAX - rows; if (top < 0) top = 0; if (sel >= BIOS_MAX) sel = 0; if (sel < 0) sel = BIOS_MAX - 1; if (sel >= top + rows) top = sel - rows + 1; if (sel < top) top = sel; if (prev_sel != sel) update = 1; pad_update(); if (Loop == LOOP_EXIT) break; } pad_wait_clear(); ui_popup_reset(); if (flag) load_background(WP_LOGO); else load_background(WP_FILER); #ifdef ADHOC if (flag != 2) #endif { if (old_bios != neogeo_bios) { if (!flag) ui_popup(TEXT(ALL_NVRAM_FILES_ARE_REMOVED)); delete_files("nvram", ".nv"); } } }
/* * module initialization function */ static int mod_init(void) { LOG(L_INFO, "permissions - initializing\n"); /* do not load the files if not necessary */ if (strlen(default_allow_file) || strlen(default_deny_file)) { if (load_file(default_allow_file, &allow, &allow_rules_num, 1) != 0) goto error; if (load_file(default_deny_file, &deny, &deny_rules_num, 1) != 0) goto error; } if (db_url && (db_mode == ENABLE_CACHE)) { /* database backend is enabled, and cache is requested -- load the DB */ if (perm_init_db()) goto error; /* prepare DB commands for trusted table */ if (init_trusted_db()) { LOG(L_ERR, "Error while preparing DB commands for trusted table\n"); goto error; } /* init trusted tables */ if (init_trusted() != 0) { LOG(L_ERR, "Error while initializing allow_trusted function\n"); goto error; } /* prepare DB commands for ipmatch table */ if (init_im_db()) { LOG(L_ERR, "Error while preparing DB commands for ipmatch table\n"); goto error; } /* init ipmatch table */ if (init_ipmatch() != 0) { LOG(L_ERR, "Error while initializing ipmatch table\n"); goto error; } /* Destory DB connection, we do not need it anymore, each child process will create its own connection */ destroy_trusted_db(); destroy_im_db(); perm_destroy_db(); } if (ip_set_list_malloc(ip_set_list_count, ip_set_list_names) < 0) goto error; if (ip_set_list_count > 0) { ip_set_list_local = pkg_malloc(ip_set_list_count*sizeof(*ip_set_list_local)); if (!ip_set_list_local) goto error; memset(ip_set_list_local, 0, sizeof(*ip_set_list_local)*ip_set_list_count); } if (ip_set_list_names) pkg_free(ip_set_list_names); /* we need not longer names in pkg memory */ return 0; error: /* free file containers */ delete_files(&allow, allow_rules_num); delete_files(&deny, deny_rules_num); /* destroy DB cmds */ destroy_trusted_db(); destroy_im_db(); /* destory DB connection */ perm_destroy_db(); /* free the cache */ clean_trusted(); clean_ipmatch(); ip_set_list_free(); return -1; }
static int opensoap_handler(request_rec *r) { apr_status_t rv = 0; char req_id[128]; char res_id[128]; int rc = 0; #ifdef DEBUG ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, "*** mod *** : start"); #endif if (strcmp(r->handler, "opensoap")) { return DECLINED; } if (r->header_only) return HTTP_BAD_REQUEST; if(r->method_number != M_POST) return HTTP_BAD_REQUEST; SetProcessInfo(); WriteLog(8,"mod_opensoap start"); /***** Read Request and Write to File ******/ rc = write_request(r, req_id); if ((rc == EXIT_FAILURE) || (rc == HTTP_INTERNAL_SERVER_ERROR)) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : write_request(r, req_id)"); return HTTP_INTERNAL_SERVER_ERROR; } else if (rc == DSO_TOO_BIG) { read_response(r, req_id); rc = delete_files(req_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : delete_files(res_id)"); } return OK; } /****** Invoke Req_Id and Get Res_ID *******/ WriteLog(9,"invoke start"); rc = InvokeOpenSOAPServer(req_id, res_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : InvokeOpenSOAPServer(req_id, res_id)"); return HTTP_INTERNAL_SERVER_ERROR; } WriteLog(9,res_id); #ifdef DEBUG ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, "*** mod *** : InvokeOpenSOAPServer req_id = %s", req_id); ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, NULL, "*** mod *** : InvokeOpenSOAPServer res_id = %s", res_id); #endif /******** Load Response form File **********/ rc = read_response(r, res_id); if ((rc == EXIT_FAILURE) || (rc == HTTP_INTERNAL_SERVER_ERROR)) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : read_response(r, res_id)"); return HTTP_INTERNAL_SERVER_ERROR; } /****** Delete Files ******/ rc = delete_files(req_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : delete_files(req_id)"); } rc = delete_files(res_id); if (rc == EXIT_FAILURE) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "*** mod_err *** : delete_files(res_id)"); } WriteLog(8,"mod_opensoap end"); return OK; }
int main(int argc, char *argv[]) { int filedes[25500]; int i, n, first, n_files; int cid, fork_number; int status; char filename[PATH_MAX]; if (argc != 2) { fprintf(stderr, "Usage: %s <number of files>\n", argv[0]); exit(1); } n = sscanf(argv[1], "%d", &n_files); if (n != 1) { fprintf(stderr, "Usage: %s <number of files>\n", argv[0]); exit(1); } first = 0; fork_number = 0; for (n = 0; n < n_files; n++) { strcpy(filename, TEMPLATE); filedes[n] = mkstemp(filename); if (filedes[n] == -1) { if (errno != EMFILE) abortx ("open() error: file = \"%s\", errno = %d", filename, errno); else { if ((cid = fork())) { if (cid == -1) abortx("Error forking child"); else { waitpid(cid, &status, 0); for (i = first; i < n; i++) if (!write_something (filedes[i])) abortx ("Error writing to files"); if (fork_number == 0) delete_files(); exit(WEXITSTATUS(status)); } } else { fork_number++; for (i = first; i < n; i++) close(filedes[i]); first = n; n--; } } } } for (i = first; i < n; i++) if (!write_something(filedes[i])) abortx("Error writing to files"); if (fork_number == 0) delete_files(); exit(0); }
static void test_random_files( CuTest* tc ) { // Setup the test segment char* segment = "seq_file"; int chunk = 1024, i = 0; // internal buffer size used by the stream lcn_directory_t *dir; char *data[] = { ".zero", ".one", ".ten", ".hundred", ".big1", ".big2", ".big3", ".big4", ".big5", ".big6", ".big7" }; int data_size = 11; lcn_compound_file_writer_t *cfw; lcn_compound_file_reader_t *cfr; apr_pool_t *pool; apr_pool_create( &pool, NULL ); LCN_TEST( lcn_fs_directory_create( &dir, dir_test, LCN_TRUE, pool ) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".zero", NULL), 0, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".one", NULL), 1, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".ten", NULL), 10, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".hundred", NULL), 100, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big1", NULL), chunk, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big2", NULL), chunk - 1, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big3", NULL), chunk + 1, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big4", NULL), 3 * chunk, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big5", NULL), 3 * chunk - 1, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big6", NULL), 3 * chunk + 1, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".big7", NULL), 1000 * chunk, pool) ); // Setup extraneous files LCN_TEST( create_random_file(tc, dir, "onetwothree", 100, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".notIn", NULL), 50, pool) ); LCN_TEST( create_random_file(tc, dir, apr_pstrcat(pool, segment, ".notIn2", NULL), 51, pool) ); LCN_TEST( lcn_compound_file_writer_create ( &cfw, dir, cf_name, pool ) ); for (i = 0; i < data_size; i++) { lcn_compound_file_writer_add_file( cfw, apr_pstrcat(pool, segment, data[i], NULL ) ); } lcn_compound_file_writer_close(cfw); LCN_TEST( lcn_compound_file_reader_create ( &cfr, dir, cf_name, pool ) ); for (i = 0; i < data_size; i++) { lcn_index_input_t *expected = NULL; lcn_index_input_t *actual = NULL; LCN_TEST( lcn_directory_open_input( dir, &expected, apr_pstrcat(pool, segment, data[i], NULL ), LCN_IO_CONTEXT_READONCE, pool ) ); LCN_TEST( lcn_compound_file_reader_open_input( cfr, &actual, apr_pstrcat(pool, segment, data[i], NULL ) ) ); assert_same_stream ( tc, expected, actual); assert_same_seek_behavior ( tc, expected, actual ); LCN_TEST ( lcn_index_input_close( expected ) ); LCN_TEST ( lcn_index_input_close( actual ) ); } LCN_TEST ( lcn_compound_file_reader_close ( cfr ) ); delete_files( tc, dir_test ); }
static void test_fs_field_bitvector( CuTest* tc ) { apr_pool_t* pool; lcn_bitvector_t* bitvector; apr_pool_create( &pool, main_pool ); /* setup the indexes */ { apr_hash_t *map; LCN_TEST( lcn_analyzer_map_create( &map, pool ) ); delete_files( tc, "fs_index_1" ); LCN_TEST( lcn_index_writer_create_index_by_dump( "fs_index_1", "fs_dump_1", map, LCN_FALSE, /* optimize */ pool )); delete_files( tc, "fs_index_2" ); LCN_TEST( lcn_index_writer_create_index_by_dump( "fs_index_2", "fs_dump_2", map, LCN_TRUE, /* optimize */ pool )); } { /* reading fixed sized fields defined in two indexes */ lcn_index_reader_t *reader1, *reader2, *reader; lcn_list_t *list; unsigned int date = 23; LCN_TEST( lcn_index_reader_create_by_path( &reader1, "fs_index_1", pool )); LCN_TEST( lcn_index_reader_create_by_path( &reader2, "fs_index_2", pool )); LCN_TEST( lcn_list_create( &list, 10, pool )); LCN_TEST( lcn_list_add( list, reader1 )); LCN_TEST( lcn_list_add( list, reader2 )); LCN_TEST( lcn_multi_reader_create_by_sub_readers( &reader, list, pool )); LCN_TEST( lcn_index_reader_fs_int_field_bitvector( reader, &bitvector, "dump2", range_function, &date, pool )); CuAssertIntEquals( tc, 24, lcn_bitvector_size( bitvector) ); CuAssertIntEquals( tc, 1, lcn_bitvector_count( bitvector )); { /* try to search an then check result */ lcn_searcher_t *searcher; lcn_query_t *query; lcn_hits_t *hits; lcn_document_t* doc; char* fval; LCN_TEST( lcn_index_searcher_create_by_reader( &searcher, reader, pool )); LCN_TEST( lcn_match_all_docs_query_create( &query, pool ) ); LCN_TEST( lcn_searcher_search( searcher, &hits, query, bitvector, pool ) ); CuAssertIntEquals( tc, 1, lcn_hits_length( hits )); LCN_TEST( lcn_hits_doc( hits, &doc, 0, pool ) ); LCN_TEST( lcn_document_get( doc, &fval, "string", pool )); CuAssertStrEquals( tc, "field23", fval ); } } apr_pool_destroy( pool ); }
intptr_t get_files(HANDLE hPlugin, struct PluginPanelItem *PanelItem, size_t ItemsNumber, int Move, UnicodeString& DestPath, OPERATION_MODES OpMode) { if ((ItemsNumber == 0) || (wcscmp(PanelItem[0].FileName, L"..") == 0)) return 1; PluginInstance* plugin = (PluginInstance*) hPlugin; bool show_dialog = (OpMode & (OPM_SILENT | OPM_FIND | OPM_VIEW | OPM_EDIT | OPM_QUICKVIEW)) == 0; bool show_error = (OpMode & (OPM_FIND | OPM_QUICKVIEW)) == 0; try { CopyFilesOptions options; options.show_dialog = show_dialog; options.show_error = show_error; options.dst_dir = DestPath; options.move_files = Move != 0; options.copy_shared = get_app_option(FSSF_SYSTEM, c_copy_opened_files_option, true); options.use_file_filters = false; options.use_tmp_files = (OpMode & (OPM_FIND | OPM_VIEW | OPM_QUICKVIEW)) != 0; if (show_dialog) { options.ignore_errors = g_plugin_options.ignore_errors; options.overwrite = g_plugin_options.overwrite; options.show_stats = g_plugin_options.show_stats; if (!show_copy_files_dlg(options, false)) BREAK; if (g_plugin_options.save_def_values) { g_plugin_options.ignore_errors = options.ignore_errors; g_plugin_options.overwrite = options.overwrite; g_plugin_options.show_stats = options.show_stats; save_def_option_values(g_plugin_options); } DestPath = options.dst_dir; } else { options.ignore_errors = false; options.overwrite = ooOverwrite; options.show_stats = ssoNever; } CopyFilesStats stats; Log log; { UiLink ui((OpMode & OPM_SILENT) != 0); if (ui.update_needed()) { draw_progress_msg(far_get_msg(MSG_PROGRESS_PREPARE)); } // source directory UnicodeString src_dir_path = plugin->current_dir; // distination directory and file name (if renaming) UnicodeString dst_dir_path, dst_new_name; FilePath dst_fp(options.dst_dir); bool dst_is_remote = !dst_fp.is_absolute || (dst_fp.root.size() == 0); if (dst_is_remote) { // ensure that file name case is correct in source and destinations paths // it will be used later in comparison FilePath src_dir_fp(src_dir_path); find_real_file_path(src_dir_fp, plugin->session); src_dir_path = src_dir_fp.get_full_path(); dst_fp = FilePath(plugin->current_dir).combine(dst_fp); find_real_file_path(dst_fp, plugin->session); } if ((dst_is_remote && dir_exists(dst_fp.get_full_path(), plugin->session)) || (!dst_is_remote && dir_exists(dst_fp.get_full_path()))) { dst_dir_path = dst_fp.get_full_path(); } else { if (ItemsNumber != 1) { dst_dir_path = dst_fp.get_full_path(); } else { dst_dir_path = dst_fp.get_dir_path(); dst_new_name = dst_fp.get_file_name(); } } UnicodeString src_file_name, dst_file_name; // store source / destination file names UnicodeString src_path, dst_path; // store source / destination file paths // list of selected files FileList panel_file_list; panel_items_to_file_list(PanelItem, ItemsNumber, panel_file_list); // verify that no file is copied into self if (dst_is_remote) { for (unsigned i = 0; i < ItemsNumber; i++) { src_file_name = panel_file_list[i].file_name; COMPOSE_PATH2(src_path, src_dir_path, src_file_name); if (dst_new_name.size() != 0) dst_file_name = dst_new_name; else dst_file_name = src_file_name; COMPOSE_PATH2(dst_path, dst_dir_path, dst_file_name); if (dst_path == src_path) FAIL(CustomError(far_get_msg(MSG_ERR_SELF_COPY), src_path)); } } // make sure destination path exists if (dst_is_remote) prepare_target_path(dst_dir_path, plugin->session, plugin); else prepare_target_path(dst_dir_path, plugin); Array<unsigned> finished_idx; // indices of processed files // try to move files remotely // mark files that were processed successfully if (options.move_files && dst_is_remote) { // prepare progress data CopyFilesProgress progress; QueryPerformanceCounter((PLARGE_INTEGER) &progress.start_time); ui.force_update(); // iterate through selected files for (unsigned i = 0; i < ItemsNumber; i++) { src_file_name = panel_file_list[i].file_name; // source file name COMPOSE_PATH2(src_path, src_dir_path, src_file_name); // source file path if (dst_new_name.size() != 0) dst_file_name = dst_new_name; else dst_file_name = src_file_name; // destination file name COMPOSE_PATH2(dst_path, dst_dir_path, dst_file_name); // destination file path // update progress bar if needed if (ui.update_needed()) { progress.src_path = src_path; progress.dst_path = dst_path; draw_move_remote_files_progress(progress, stats); } // try to move file remotely if (move_remote_file(src_path, dst_path, plugin->session)) { // update stats if (panel_file_list[i].is_dir()) stats.dirs++; else stats.files++; // add finished file to list finished_idx += i; } } } // scan source directories and prepare lists of files to process ObjectArray<FileList> file_lists; ui.force_update(); CreateListStats list_stats; CreateListOptions list_options; list_options.ignore_errors = options.ignore_errors; list_options.show_error = options.show_error; try { for (unsigned i = 0; i < ItemsNumber; i++) { if (finished_idx.bsearch(i) == -1) { file_lists += create_file_list(src_dir_path, panel_file_list[i].file_name, list_stats, list_options, ui, log, plugin->session, plugin); } else file_lists += FileList(); // skip already moved objects } } finally (stats.errors = list_stats.errors); // show file filters dialog if needed ObjectArray<FilterInterface> filters; if (options.use_file_filters && !dst_is_remote && show_dialog) { load_file_filters(); if (export_filter_list.size() != 0) { Array<FilterSelection> selection; if (!show_filters_dlg(export_filter_list, selection)) BREAK; for (unsigned i = 0; i < selection.size(); i++) { filters += FilterInterface(export_filter_list[selection[i].src_idx].src_ext, export_filter_list[selection[i].src_idx][selection[i].dst_idx].dst_ext, export_filter_list[selection[i].src_idx][selection[i].dst_idx].guid); } } } // perform copy CopyFilesProgress progress; progress.total_size = list_stats.size; progress.processed_total_size = progress.copied_total_size = 0; QueryPerformanceCounter((PLARGE_INTEGER) &progress.start_time); ui.force_update(); AutoBuffer buffer(g_plugin_options.copy_buf_size); for (unsigned i = 0; i < ItemsNumber; i++) { if (finished_idx.bsearch(i) == -1) { copy_files(true, src_dir_path, file_lists[i], dst_is_remote, dst_dir_path, dst_new_name, stats, progress, options, ui, buffer, log, filters, plugin->session, plugin); } PanelItem[i].Flags &= ~PPIF_SELECTED; } // delete source files if moving (only if no errors or skipped files to prevent data loss) if (options.move_files && (stats.errors == 0) && (stats.skipped == 0)) { DeleteFilesStats del_stats; DeleteFilesOptions del_options; del_options.ignore_errors = options.ignore_errors; del_options.show_stats = options.show_stats; del_options.show_error = options.show_error; del_options.show_dialog = options.show_dialog; DeleteFilesProgress del_progress; del_progress.objects = 0; del_progress.total_objects = list_stats.files + list_stats.dirs; QueryPerformanceCounter((PLARGE_INTEGER) &del_progress.start_time); ui.force_update(); try { for (unsigned i = 0; i < ItemsNumber; i++) { delete_files(true, src_dir_path, file_lists[i], del_stats, del_progress, del_options, ui, log, plugin->session, plugin); } } finally (stats.errors += del_stats.errors); } // set cursor to new file name after rename if (dst_is_remote && options.move_files && (src_dir_path == dst_dir_path)) { assert(dst_new_name.size() != 0); far_control_int(plugin, FCTL_UPDATEPANEL, 1); PanelInfo panel_info; far_control_ptr(plugin, FCTL_GETPANELINFO, &panel_info); PanelRedrawInfo redraw_info = { sizeof(PanelRedrawInfo) }; redraw_info.TopPanelItem = panel_info.TopPanelItem; redraw_info.CurrentItem = panel_info.CurrentItem; for (size_t i = 0; i < panel_info.ItemsNumber; i++) { PluginPanelItem* ppi = far_get_panel_item(plugin, i, panel_info); UnicodeString file_name = ppi->FileName; if (file_name == dst_new_name) { redraw_info.CurrentItem = i; break; } } far_control_ptr(INVALID_HANDLE_VALUE, FCTL_REDRAWPANEL, &redraw_info); } } if (show_dialog && ((options.show_stats == ssoAlways) || ((options.show_stats == ssoIfError) && (stats.errors != 0)))) show_copy_files_results_dlg(stats, log); return 1; }
static void test_sort_top_docs_impl( CuTest* tc, lcn_bool_t reverse ) { apr_pool_t *pool; lcn_searcher_t *searcher; lcn_query_t *query; lcn_hits_t *hits; lcn_list_t *sort_fields; unsigned int i, prev, next; { apr_hash_t* map; apr_pool_create( &pool, main_pool ); delete_files( tc, "sort_test" ); LCN_TEST( lcn_analyzer_map_create( &map, pool ) ); LCN_TEST( lcn_index_writer_create_index_by_dump( "sort_test", "sort.txt", map, LCN_TRUE, /* optimize */ pool )); apr_pool_destroy( pool ); } apr_pool_create( &pool, main_pool ); LCN_TEST( lcn_index_searcher_create_by_path( &searcher, "sort_test", pool )); LCN_TEST( lcn_match_all_docs_query_create( &query, pool )); LCN_TEST( lcn_list_create( &sort_fields, 1, pool )); { lcn_sort_field_t *sfield; LCN_TEST( lcn_sort_field_create( &sfield, "int_field", LCN_SORT_FIELD_INT, reverse, pool ) ); LCN_TEST( lcn_list_add( sort_fields, sfield ) ); } LCN_TEST( lcn_searcher_search_sort( searcher, &hits, query, NULL, sort_fields, pool ) ); prev = reverse ? 100000 : 0 ; for( i = 0; i < lcn_hits_length( hits ); i++ ) { lcn_document_t* doc; char* id; apr_status_t s; LCN_TEST( lcn_hits_doc( hits, &doc, i, pool ) ); s = lcn_document_get( doc, &id, "int_field", pool ); if ( APR_SUCCESS == s ) { next = atoi( id ); } else { next = 0; } CuAssertTrue( tc, (reverse ? next <= prev : next >= prev ) ); prev = next; } apr_pool_destroy( pool ); }
int main(int argc, char *argv[]) { argv0 = argv[0]; shrc rc; // htmllabel stree:initcall // initialize connection to server SH_DO(Shore::init(argc, argv, 0, getenv("DOC_INDEX_RC"))); // get command-line options int c; while ((c = getopt(argc,argv,"aldpV")) != EOF) switch(c) { case 'a': operation = OP_ADD; break; case 'l': operation = OP_LIST; break; case 'd': operation = OP_DEL; break; case 'p': operation = OP_POOL_LIST; break; case 'V': verbose++; break; default: usage(); } if (operation == OP_NONE) usage(); // Start a transaction for initialization SH_BEGIN_TRANSACTION(rc); if (rc) rc.fatal(); // this terminates the program with extreme prejudice // Check that our demo directory exists rc = Shore::chdir(DEMO_DIR); if (rc != RCOK) { if (rc != RC(SH_NotFound)) SH_ABORT_TRANSACTION(rc); // Not found. Must be the first time through. // Create the directory SH_DO(Shore::mkdir(DEMO_DIR, 0755)); SH_DO(Shore::chdir(DEMO_DIR)); // htmllabel stree:createrepository // Make a new DocIndex object ... repository = new("repository", 0644) DocIndex; repository.update()->initialize(); // ... and a pool for allocating Nodes. SH_DO(nodes.create_pool("pool", 0644, nodes)); } else { // not first time // Get the repository root from the database ... SH_DO(Ref<DocIndex>::lookup("repository",repository)); // ... and the pool for creating nodes SH_DO(nodes.lookup("pool", nodes)); } SH_DO(SH_COMMIT_TRANSACTION); switch (operation) { case OP_ADD: add_files(argc-optind, argv+optind); break; case OP_LIST: if (optind != argc-1) usage(); list_files(argv[optind]); break; case OP_DEL: delete_files(argc-optind, argv+optind); break; case OP_POOL_LIST: pool_list(); break; default: break; } return 0; } // main
/* * === FUNCTION ====================================================================== * Name: append_files * Description: Appends files to archive referred to by 'arch'. If one or files * already in the archive matches a file to be added, calls delete_files() * with the list of the existing files.o * * Pre: 'arch' refers to an archive file that is open, readable, and * writable. 'files' contains the pathnames of existing files that are * readable, and 'count' is the number of those files. * ===================================================================================== */ static void append_files(int arch, char *archname, char **files, int count) { char *new_files[count]; int new_arch; int i; if(!(new_arch = isempty_arch(archname))) { for(i = 0; i < count; i++) new_files[i] = files[i]; printf("I'm here!"); /* NULL out any files in 'existing_files' * that don't already exist in archive */ map_over_members(arch, check_members, new_files, count, -1); } /* Seek to end of file */ lseek(arch, 0, SEEK_END); struct ar_hdr new_hdr; char *fname; int new_fd; size_t to_write; for(i = 0; i < count; i++) { fname = files[i]; if(isdir(fname)) { fprintf(stderr, "%s is a directory\n", fname); exit(EXIT_FAILURE); } else if(strcmp(archname, fname) == 0) { /* This is something I wish I could * have fixed, but my attempts at copying * the archive to a temporary file and then * appending its contents ate up a lot of * time and ended in failure. */ fprintf(stderr, "cannot add archive to itself\n"); } if(fname != NULL) { fill_ar_hdr(fname, &new_hdr); if(write(arch, &new_hdr, SARFHDR) == -1) { perror("write"); fprintf(stderr, "failed to write header to archive\n"); goto cleanup; } if((new_fd = open(fname, O_RDONLY | O_EXCL)) == -1) { perror("open"); fprintf(stderr, "failed to open file %s\n", fname); goto cleanup; } to_write = get_file_size(new_fd); write_to_arch(new_fd, arch, to_write); } } if(!new_arch) { for(i = 0; i < count; i++) if(new_files[i] != NULL) files[i] = NULL; for(i = 0; i < count; i++) { if(files[i] != NULL) { delete_files(arch, archname, files, count); break; } } } cleanup: if(close(arch) == -1) { perror("read"); fprintf(stderr, "error closing archive file\n"); exit(EXIT_FAILURE); } return; }
int main( int argc, char ** argv) { uint32_t rtn = 0; uint32_t action = 0; CAMCameraListPtr pList = 0; CAMDeviceInfoPtr pDevInfo = 0; CAMHandle hCam = 0; CAMDevice device; OPTS opts; action = parse_options( &opts, argc, argv); if (!action) return 0; do { SetUsbDebug( verbose); rtn = InitUsb(); if (rtn) break; rtn = GetCameraList( &pList, (opts.flags & OPT_FORCE)); if (rtn) break; if (action == ACT_LIST_DEVICES) { list_devices( pList); break; } device = SelectCamera( &opts, pList); if (!device) break; if (action == ACT_DEVICE_RESET) { ResetCamera( device); break; } rtn = InitCamera( device, &hCam); if (rtn) break; rtn = GetDeviceInfo( hCam, &pDevInfo); if (rtn) break; switch (action) { case ACT_SHOW_INFO: show_info( pDevInfo); break; case ACT_LIST_OPERATIONS: list_operations( pDevInfo); break; case ACT_STORAGE_INFO: show_storage_info( hCam, pDevInfo); break; case ACT_LIST_PROPERTIES: list_properties( pDevInfo); break; case ACT_GETSET_PROPERTY: getset_property( hCam, pDevInfo, &opts); break; case ACT_LIST_FILES: list_files( hCam, pDevInfo); break; case ACT_LIST_HANDLES: list_handles( hCam, pDevInfo); break; case ACT_HANDLE_INFO: show_handle_info( hCam, pDevInfo, &opts); break; case ACT_GET_FILE: get_files( hCam, pDevInfo, &opts); break; case ACT_DELETE_FILE: delete_files( hCam, pDevInfo, &opts); break; } } while (0); if (rtn) camcli_error( GetErrorName( pDevInfo, rtn)); free( pDevInfo); free( pList); TermCamera( &hCam); TermUsb(); return 0; }