void my_mkdir_r(char *path) { int i,len; char str[512]; strncpy(str,path,512); len = strlen(str); for(i=0; i < len ; i++) { if(str[i] == '/' && i != 0) { str[i] = '\0'; if(access(str,F_OK) != 0) { my_mkdir(str); } str[i] = '/'; } } if(len > 0 && access(str,F_OK) != 0) { my_mkdir(str); } }
/* Assumes num argument will be NULL for a host RRD. */ int write_data_to_rrd ( const char *source, const char *host, const char *metric, const char *sum, const char *num, unsigned int step, unsigned int process_time, ganglia_slope_t slope) { char rrd[ PATHSIZE ]; char *summary_dir = "__SummaryInfo__"; /* Build the path to our desired RRD file. Assume the rootdir exists. */ strcpy(rrd, gmetad_config.rrd_rootdir); if (source) { strncat(rrd, "/", PATHSIZE); strncat(rrd, source, PATHSIZE); my_mkdir( rrd ); } if (host) { strncat(rrd, "/", PATHSIZE); strncat(rrd, host, PATHSIZE); my_mkdir( rrd ); } else { strncat(rrd, "/", PATHSIZE); strncat(rrd, summary_dir, PATHSIZE); my_mkdir( rrd ); } strncat(rrd, "/", PATHSIZE); strncat(rrd, metric, PATHSIZE); strncat(rrd, ".rrd", PATHSIZE); return push_data_to_rrd( rrd, sum, num, step, process_time, slope); }
void mkdir_cmd (void) { char *tempdir; char *dir; dir = input_expand_dialog (_("Create a new Directory"), _(" Enter directory name:"), ""); if (!dir || !*dir) return; if (dir[0] == '/' || dir[0] == '~') tempdir = g_strdup (dir); else tempdir = concat_dir_and_file (current_panel->cwd, dir); g_free (dir); save_cwds_stat (); if (my_mkdir (tempdir, 0777) == 0) { update_panels (UP_OPTIMIZE, tempdir); repaint_screen (); select_item (current_panel); g_free (tempdir); return; } g_free (tempdir); message (1, MSG_ERROR, " %s ", unix_error_string (errno)); }
void mkdir_cmd (void) { char *dir, *absdir; dir = input_expand_dialog (_("Create a new Directory"), _(" Enter directory name:"), MC_HISTORY_FM_MKDIR, ""); if (!dir) return; if (dir[0] == '/' || dir[0] == '~') absdir = g_strdup (dir); else absdir = mhl_str_dir_plus_file (current_panel->cwd, dir); save_cwds_stat (); if (my_mkdir (absdir, 0777) == 0) { update_panels (UP_OPTIMIZE, dir); repaint_screen (); select_item (current_panel); } else { message (1, MSG_ERROR, " %s ", unix_error_string (errno)); } g_free (absdir); g_free (dir); }
/* * make a backup of users .newsrc in case of the bogie man */ void backup_newsrc( void) { char dirbuf[PATH_LEN]; char filebuf[PATH_LEN]; struct stat statbuf; #ifdef NNTP_ABLE if (read_news_via_nntp && !read_saved_news && nntp_tcp_port != IPPORT_NNTP) snprintf(filebuf, sizeof(filebuf), "%s:%d", nntp_server, nntp_tcp_port); else #endif /* NNTP_ABLE */ { STRCPY(filebuf, nntp_server); } JOINPATH(dirbuf, rcdir, filebuf); joinpath(filebuf, dirbuf, OLDNEWSRC_FILE); if (-1 == stat(dirbuf, &statbuf)) { if (-1 == my_mkdir(dirbuf, (mode_t) (S_IRWXU))) /* Can't create directory: Fall back on Homedir */ joinpath(filebuf, homedir, OLDNEWSRC_FILE); } if (!backup_file(newsrc, filebuf)) error_message(_(txt_filesystem_full_backup), NEWSRC_FILE); }
/* Assumes num argument will be NULL for a host RRD. */ int write_data_to_rrd ( const char *source, const char *host, const char *metric, const char *sum, const char *num, unsigned int step, unsigned int process_time, ganglia_slope_t slope) { apr_time_t start = apr_time_now(), now; char rrd[ PATHSIZE + 1 ]; char *summary_dir = "__SummaryInfo__"; int i; int ret; /* Build the path to our desired RRD file. Assume the rootdir exists. */ strncpy(rrd, gmetad_config.rrd_rootdir, PATHSIZE); if (source) { strncat(rrd, "/", PATHSIZE-strlen(rrd)); strncat(rrd, source, PATHSIZE-strlen(rrd)); my_mkdir( rrd ); } if (host) { strncat(rrd, "/", PATHSIZE-strlen(rrd)); i = strlen(rrd); strncat(rrd, host, PATHSIZE-strlen(rrd)); if(gmetad_config.case_sensitive_hostnames == 0) { /* Convert the hostname to lowercase */ for( ; rrd[i] != 0; i++) rrd[i] = tolower(rrd[i]); } my_mkdir( rrd ); } else { strncat(rrd, "/", PATHSIZE-strlen(rrd)); strncat(rrd, summary_dir, PATHSIZE-strlen(rrd)); my_mkdir( rrd ); } strncat(rrd, "/", PATHSIZE-strlen(rrd)); strncat(rrd, metric, PATHSIZE-strlen(rrd)); strncat(rrd, ".rrd", PATHSIZE-strlen(rrd)); ret = push_data_to_rrd( rrd, sum, num, step, process_time, slope); now = apr_time_now(); ganglia_scoreboard_incby(METS_ALL_DURATION, now - start); ganglia_scoreboard_incby(METS_RRDTOOLS_DURATION, now - start); return ret; }
static int build_dir() { if (remove_or_rename == RENAME_IDC_FILE) return ( my_mkdir(mmap_tmpfile_dirpath) | my_mkdir(idc_mmap_file_dirpath) | my_mkdir(cdn_mmap_file_dirpath) | my_mkdir(url_mmap_file_dirpath) | my_mkdir(idc_rename_dirpath)); else return ( my_mkdir(mmap_tmpfile_dirpath) | my_mkdir(idc_mmap_file_dirpath) | my_mkdir(cdn_mmap_file_dirpath) | my_mkdir(url_mmap_file_dirpath)); }
void file_test(){ my_mkdir("usr/data"); show_file_list(); printf("\n"); my_mkdir("src"); my_mkdir("../usr/./data/data1"); show_file_list(); printf("\n"); int fd; fd = my_create("usr/.././usr/data/.././data/data1/file1"); show_file_list(); my_close(fd); fd = my_open("usr/.././usr/data/.././data/data1/file1"); my_close(fd); show_file_list(); }
bool dir_create(const char *path) { const char *ptr; char buf[512]; /* If the directory already exists then we're done */ if (dir_exists(path)) return TRUE; #ifdef WINDOWS /* If we're on windows, we need to skip past the "C:" part. */ if (isalpha(path[0]) && path[1] == ':') path += 2; #endif /* Iterate through the path looking for path segements. At each step, * create the path segment if it doesn't already exist. */ for (ptr = path; *ptr; ptr++) { if (*ptr == PATH_SEPC) { /* Find the length of the parent path string */ size_t len = (size_t)(ptr - path); /* Skip the initial slash */ if (len == 0) continue; /* If this is a duplicate path separator, continue */ if (*(ptr - 1) == PATH_SEPC) continue; /* We can't handle really big filenames */ if (len - 1 > 512) return FALSE; /* Create the parent path string, plus null-padding */ my_strcpy(buf, path, len + 1); /* Skip if the parent exists */ if (dir_exists(buf)) continue; /* The parent doesn't exist, so create it or fail */ if (my_mkdir(buf, 0755) != 0) return FALSE; } } return my_mkdir(path, 0755) == 0 ? TRUE : FALSE; }
void rename_test(){ int fd; show_file_list(); char filename[40]; char changename[40]; printf("\n"); if(my_rename("/usr/data/data1/file1", "/usr/data/data1/file1_1") != OK){ printf("rename error!!\n"); return; } show_file_list(); printf("\n"); if(my_mkdir("usr/data/manyfile") != OK){ printf("mkdir error!!\n"); return; } show_file_list(); printf("\n"); int i = 35; memset(filename, 0, 40); memset(changename, 0, 40); strcpy(filename, "usr/data/manyfile/file"); strcpy(changename, "usr/data/manyfile/file"); int length = strlen(filename); for(; i < 65; ++i){ filename[length] = (char)i; if(fd = my_create(filename) < 0){ my_close(fd); printf("create file error when i = %d\n", i); return; } my_close(fd); } show_file_list(); printf("\n"); /* int i = 30; */ /* changename[length] = (char)70; */ /* printf("changename is %s, length is %d\n",changename, length); */ /* printf("filename is %s, length is %d\n",filename, length); */ /* exit(0); */ for( i = 35; i < 65; ++i){ filename[length] = (char)i; changename[length] = (char)(100 - i); if(my_rename(filename, changename) != OK){ printf("rename error when i = %d!!\n", i); return; } } show_file_list(); printf("\n"); }
/* ------------------------------------------------------- * make_dir: * must understand perfectly!!! * * Takes a pathname as parameter * * (1) set the device * (2) get parent MINODE by using dirname with * getino * Load MINODE using iget * (3) call my_mkdir(MINODE* parent, char* name) * --------------------------------------------------------*/ void make_dir(char* path) { MINODE* pip; // parent MINODE* int dev, pino; // device, parent ino // parent = path to parent directory, child = basename char* parent, *child; // (1) Set device according to relative or absolute path if(path[0] == '/') dev = root->dev; else dev = running->cwd->dev; // (2) Separate path into dirname and basename parent = strdup(Dirname(path)); // make copies child = strdup(Basename(path)); // Debug print //printf("parent: %s\n", parent); //printf("child: %s\n", child); // (3) get in memory MINODE of parent directory pino = getino(&dev, parent); // First, get parent ino pip = iget(dev, pino); // Then use it to load INODE into minode[] table // (4) Error checking on found MINODE if(pip == NULL) // (4.1) ensure the MINODE was found { printf("Error: unable to locate %s\n", parent); } else if(!isdir(pip)) // (4.2) is DIR { printf("Error: %s is not a directory\n", parent); } else if(search(pip, child) != 0) // (4.3) child does not already exist { // the child was already found printf("Error: %s already exists in %s\n", child, parent); } // (5) We've verified that parent path exists, is a directory // and child does not exist in it, so add to it else my_mkdir(pip,child); // No matter what, dont forget to write back! // Release parent from minode[] table and write back to disk iput(pip); }
void mkdir_cmd (void) { char *dir; const char *name = ""; /* If 'on' then automatically fills name with current selected item name */ if (auto_fill_mkdir_name && !DIR_IS_DOTDOT (selection (current_panel)->fname)) name = selection (current_panel)->fname; dir = input_expand_dialog (_("Create a new Directory"), _("Enter directory name:"), MC_HISTORY_FM_MKDIR, name, INPUT_COMPLETE_FILENAMES); if (dir != NULL && *dir != '\0') { vfs_path_t *absdir; if (dir[0] == '/' || dir[0] == '~') absdir = vfs_path_from_str (dir); else { /* possible escaped '~' */ /* allow create directory with name '~' */ char *tmpdir = dir; if (dir[0] == '\\' && dir[1] == '~') tmpdir = dir + 1; absdir = vfs_path_append_new (current_panel->cwd_vpath, tmpdir, NULL); } save_cwds_stat (); if (my_mkdir (absdir, 0777) == 0) { update_panels (UP_OPTIMIZE, dir); repaint_screen (); select_item (current_panel); } else { message (D_ERROR, MSG_ERROR, "%s", unix_error_string (errno)); } vfs_path_free (absdir); } g_free (dir); }
static ds_ctxt_t * local_init(const char *root) { ds_ctxt_t *ctxt; if (my_mkdir(root, 0777, MYF(0)) < 0 && my_errno != EEXIST) { my_error(EE_CANT_MKDIR, MYF(ME_BELL | ME_WAITTANG), root, my_errno); return NULL; } ctxt = my_malloc(sizeof(ds_ctxt_t), MYF(MY_FAE)); ctxt->root = my_strdup(root, MYF(MY_FAE)); return ctxt; }
static char *create_tmpdir(const char *progname) { static char test_dirname[FN_REFLEN]; char tmp_name[FN_REFLEN]; uint length; /* Create a temporary directory of name TMP-'executable', but without the -t extension */ fn_format(tmp_name, progname, "", "", MY_REPLACE_DIR | MY_REPLACE_EXT); length= strlen(tmp_name); if (length > 2 && tmp_name[length-2] == '-' && tmp_name[length-1] == 't') tmp_name[length-2]= 0; strxmov(test_dirname, "TMP-", tmp_name, NullS); /* Don't give an error if we can't create dir, as it may already exist from a previously aborted run */ (void) my_mkdir(test_dirname, 0777, MYF(0)); return test_dirname; }
void mkdir_cmd (void) { char *dir, *absdir; const char *name = ""; /* If 'on' then automatically fills name with current selected item name */ if (auto_fill_mkdir_name && strcmp (selection (current_panel)->fname, "..") != 0) name = selection (current_panel)->fname; dir = input_expand_dialog (_("Create a new Directory"), _("Enter directory name:"), MC_HISTORY_FM_MKDIR, name); if (!dir) return; if (*dir) { if (dir[0] == '/' || dir[0] == '~') absdir = g_strdup (dir); else absdir = concat_dir_and_file (current_panel->cwd, dir); save_cwds_stat (); if (my_mkdir (absdir, 0777) == 0) { update_panels (UP_OPTIMIZE, dir); repaint_screen (); select_item (current_panel); } else { message (D_ERROR, MSG_ERROR, "%s", unix_error_string (errno)); } g_free (absdir); } g_free (dir); }
int main(int argc, char **argv) { my_init_lib(); // create a simple file tfunc_gen_and_check_file_zbin("/file1.txt", 1025); // create a simple directory tfunc_dir_make("/dir1"); /* * Test errors creating files */ // condition 1: try to create a file in a non existent directory if (my_open("/dir2/file2.txt",O_CREATE) >= 0) { printf("[test] open failed condition 1.\n"); exit(-1); } // condition 2: use the name of a file as subdirectory name in a path if (my_open("/file1.txt/file2.txt",O_CREATE) >= 0) { printf("[test] open failed condition 2.\n"); exit(-1); } // condition 3: use a path without the root if (my_open("file3.txt",O_CREATE) >= 0) { printf("[test] open failed: condition 3.\n"); exit(-1); } // condition 4: use the name of wrong double slash directory if (my_open("//file2.txt",O_CREATE) >= 0) { printf("[test] open failed: condition 4.\n"); exit(-1); } /* * Test errors creating directories */ // condition 1: try to create a directory in a non existent directory if (my_mkdir("/dir2/dir2") != -1) { printf("[test] mkdir failed: condition 1.\n"); exit(-1); } // condition 2: try to create a directory already existent if (my_mkdir("/dir1") != -1) { printf("[test] mkdir failed: condition 2.\n"); exit(-1); } // condition 3: use the name of an existent file if (my_mkdir("/file1.txt") != -1) { printf("[test] mkdir failed: condition 3.\n"); exit(-1); } // condition 4: use the name of a file as subdirectory name in a path if (my_mkdir("/file1.txt/dir2") != -1) { printf("[test] mkdir failed: condition 4.\n"); exit(-1); } // condition 5: create a double shashed directory with subdirs if (my_mkdir("//dir2") != -1) { printf("[test] mkdir failed: condition 5.\n"); exit(-1); } // condition 6: create directory without the root slash if (my_mkdir("dir2") != -1) { printf("[test] mkdir failed: condition 6.\n"); exit(-1); } /* * Check that after all this mess '/' contains only 'file1.txt' and 'dir1' */ char* buf; int numberOfFiles; if(my_listdir("/",&buf, &numberOfFiles)<0){ printf("[test] failed: error listing directory.\n"); return -1; } printf("Contents of '/':\n"); tfunc_dir_print(buf,numberOfFiles); if (numberOfFiles != 2) { printf("[test] failed: wrong number of files in directory.\n"); return -1; } if(tfunc_dir_search_file("file1.txt",buf,numberOfFiles) <= 0) { printf("[test] failed: '/file1.txt' not found.\n"); return -1; } if(tfunc_dir_search_file("dir1",buf,numberOfFiles) <= 0) { printf("[test] failed: '/dir1' not found.\n"); return -1; } free(buf); printf("[test] passed.\n"); return 0; }
char *par_mktmpdir ( char **argv ) { int i; const char *tmpdir = NULL; const char *key = NULL , *val = NULL; /* NOTE: all arrays below are NULL terminated */ const char *temp_dirs[] = { P_tmpdir, #ifdef WIN32 "C:\\TEMP", #endif ".", NULL }; const char *temp_keys[] = { "PAR_TMPDIR", "TMPDIR", "TEMPDIR", "TEMP", "TMP", NULL }; const char *user_keys[] = { "USER", "USERNAME", NULL }; const char *subdirbuf_prefix = "par-"; const char *subdirbuf_suffix = ""; char *progname = NULL, *username = NULL; char *stmpdir = NULL, *top_tmpdir = NULL; int f, j, k, stmp_len = 0; char sha1[41]; SHA_INFO sha_info; unsigned char buf[32768]; unsigned char sha_data[20]; if ( (val = par_getenv(PAR_TEMP)) && strlen(val) ) { par_setup_libpath(val); return strdup(val); } #ifdef WIN32 { DWORD buflen = MAXPATHLEN; username = malloc(MAXPATHLEN); GetUserName((LPTSTR)username, &buflen); // FIXME this is uncondifionally overwritten below - WTF? } #endif /* Determine username */ username = get_username_from_getpwuid(); if ( !username ) { /* fall back to env vars */ for ( i = 0 ; username == NULL && (key = user_keys[i]); i++) { if ( (val = par_getenv(key)) && strlen(val) ) username = strdup(val); } } if ( username == NULL ) username = "******"; /* sanitize username: encode all bytes as 2 hex digits */ { char *hexname = malloc(2 * strlen(username) + 1); char *u, *h; for ( u = username, h = hexname ; *u != '\0' ; u++, h += 2) sprintf(h, "%02x", *(unsigned char*)u); username = hexname; } /* Try temp environment variables */ for ( i = 0 ; tmpdir == NULL && (key = temp_keys[i]); i++ ) { if ( (val = par_getenv(key)) && strlen(val) && isWritableDir(val) ) { tmpdir = strdup(val); break; } } #ifdef WIN32 /* Try the windows temp directory */ if ( tmpdir == NULL && (val = par_getenv("WinDir")) && strlen(val) ) { char* buf = malloc(strlen(val) + 5 + 1); sprintf(buf, "%s\\temp", val); if (isWritableDir(buf)) { tmpdir = buf; } else { free(buf); } } #endif /* Try default locations */ for ( i = 0 ; tmpdir == NULL && (val = temp_dirs[i]) && strlen(val) ; i++ ) { if ( isWritableDir(val) ) { tmpdir = strdup(val); } } /* "$TEMP/par-$USER" */ stmp_len = strlen(tmpdir) + strlen(subdirbuf_prefix) + strlen(username) + strlen(subdirbuf_suffix) + 1024; /* stmpdir is what we are going to return; top_tmpdir is the top $TEMP/par-$USER, needed to build stmpdir. NOTE: We need 2 buffers because snprintf() can't write to a buffer it is also reading from. */ top_tmpdir = malloc( stmp_len ); sprintf(top_tmpdir, "%s%s%s%s", tmpdir, dir_sep, subdirbuf_prefix, username); #ifdef WIN32 _mkdir(top_tmpdir); /* FIXME bail if error (other than EEXIST) */ #else { if (mkdir(top_tmpdir, 0700) == -1 && errno != EEXIST) { fprintf(stderr, "%s: creation of private subdirectory %s failed (errno=%i)\n", argv[0], top_tmpdir, errno); return NULL; } if (!isSafeDir(top_tmpdir)) { fprintf(stderr, "%s: private subdirectory %s is unsafe (please remove it and retry your operation)\n", argv[0], top_tmpdir); return NULL; } } #endif stmpdir = malloc( stmp_len ); /* Doesn't really work - XXX */ val = par_getenv( "PATH" ); if (val != NULL) progname = par_findprog(argv[0], strdup(val)); if (progname == NULL) progname = argv[0]; /* If invoked as "/usr/bin/parl foo.par myscript.pl" then progname should * be ".../parl", and we don't want to base our checksum on that, but * rather on "foo.par". */ { #ifdef WIN32 #define STREQ(a,b) (strcasecmp(a,b) == 0) #else #define STREQ(a,b) (strcmp(a,b) == 0) #endif int prog_len = strlen(progname); int parl_len = strlen(PARL_EXE); if (prog_len >= parl_len && STREQ(progname + prog_len - parl_len, PARL_EXE) && (prog_len == parl_len || progname[prog_len - parl_len - 1] == dir_sep[0]) && argv[1] && strlen(argv[1]) >= 4 && STREQ(argv[1] + strlen(argv[1]) - 4, ".par")) progname = argv[1]; #undef STREQ } if ( !par_env_clean() && (f = open( progname, O_RDONLY | OPEN_O_BINARY ))) { lseek(f, -18, 2); read(f, buf, 6); if(buf[0] == 0 && buf[1] == 'C' && buf[2] == 'A' && buf[3] == 'C' && buf[4] == 'H' && buf[5] == 'E') { /* pre-computed cache_name in this file */ /* "$TEMP/par-$USER/cache-$cache_name" */ lseek(f, -58, 2); read(f, buf, 41); sprintf( stmpdir, "%s%scache-%s%s", top_tmpdir, dir_sep, buf, subdirbuf_suffix ); } else { /* "$TEMP/par-$USER/cache-$SHA1" */ lseek(f, 0, 0); sha_init( &sha_info ); while( ( j = read( f, buf, sizeof( buf ) ) ) > 0 ) { sha_update( &sha_info, buf, j ); } close( f ); sha_final( sha_data, &sha_info ); for( k = 0; k < 20; k++ ) { sprintf( sha1+k*2, "%02x", sha_data[k] ); } sha1[40] = '\0'; sprintf( stmpdir, "%s%scache-%s%s", top_tmpdir, dir_sep, sha1, subdirbuf_suffix ); } } else { int i = 0; /* "$TEMP/par-$USER/temp-$PID" */ par_setenv("PAR_CLEAN", "1"); sprintf( stmpdir, "%s%stemp-%u%s", top_tmpdir, dir_sep, getpid(), subdirbuf_suffix ); /* Ensure we pick an unused directory each time. If the directory already exists when we try to create it, bump a counter and try "$TEMP/par-$USER/temp-$PID-$i". This will guard against cases where a prior invocation crashed leaving garbage in a temp directory that might interfere. */ while (my_mkdir(stmpdir, 0700) == -1 && errno == EEXIST) { sprintf( stmpdir, "%s%stemp-%u-%u%s", top_tmpdir, dir_sep, getpid(), ++i, subdirbuf_suffix ); } } free(top_tmpdir); /* set dynamic loading path */ par_setenv(PAR_TEMP, stmpdir); par_setup_libpath( stmpdir ); return stmpdir; }
void dir_test(){ struct inode* root_inode; struct inode *rip; char string[DIRSIZ]; int number; int * inode_num = & number; int r; root_inode = get_inode(1); if(root_inode == NIL_INODE){ printf("root_inode is a null inode\n"); return; } /* printf("root_inode size is %d\n", root_inode->i_size); */ /* delete_dir(root_inode, 0); */ /* empty_inode_space(root_inode); */ /* put_inode(root_inode); */ /* return; */ /* my_strcpy(string, "usr"); */ /* if( r = search_dir(root_inode, string, inode_num, LOOK_UP) != OK){ */ /* printf("LOOK_UP a usr error: %s\n", strerror(r)); */ /* put_inode(root_inode); */ /* return; */ /* } */ /* printf("this time i node size is %d\n", root_inode->i_size); */ /* put_inode(root_inode); */ /* return; */ my_strcpy(string, ".."); *inode_num = root_inode->i_num; if (r = search_dir(root_inode, string, inode_num, ENTER) != OK){ printf("enter a item error: %s\n", strerror(r)); put_inode(root_inode); return; } my_strcpy(string, "."); *inode_num = root_inode->i_num; if (r = search_dir(root_inode, string, inode_num, ENTER) != OK){ printf("enter a item error: %s\n", strerror(r)); put_inode(root_inode); return; } root_inode->i_dirt = DIRTY; put_inode(root_inode); show_file_list(); /* return; */ printf("\n"); my_strcpy(string, "."); root_inode = get_inode(1); *inode_num = 0; if (r = search_dir(root_inode, string, inode_num, LOOK_UP) != OK){ printf("find a item error: %s\n", strerror(r)); put_inode(root_inode); return; } if(*inode_num != root_inode->i_num){ printf("can't find . in the root directory!!!\n"); put_inode(root_inode); return; } put_inode(root_inode); my_mkdir("./usr"); my_mkdir("src"); my_mkdir("../root"); show_file_list(); printf("\n"); root_inode = last_dir("./../usr", string); if(root_inode == NIL_INODE){ printf("last_dir error: can't find root dir\n"); return; } if(root_inode->i_num != 1){ printf("this time last dir is not root_inode, it's i_num is %d\n", root_inode->i_num); put_inode(root_inode); return; } printf("string remain is %s\n", string); show_file_list(); printf("\n"); rip = advance(root_inode, string); if(rip == NIL_INODE){ printf("advance error: can't find usr dir\n"); return; } show_file_list(); printf("\n"); put_inode(rip); put_inode(root_inode); if(my_rmdir("/src") != OK){ printf("can't remove dir src\n"); return; } show_file_list(); }
void test_rename(char *workdir) { char file1[1024], file2[1024], link[1024], subdir[1024], newdir[1024]; struct stat sb1, sb2; int fd; printf("testing rename\n"); sprintf(file1, "%s/file1", workdir); sprintf(file2, "%s/file2", workdir); /* test stat first.. since we need it to test rename */ my_stat(file1, &sb1); /* Not much to look at, really.. how about making sure that the modification time of the file is not in the future. allow ten seconds of slack */ if (sb1.st_mtime > time(NULL) + 10) { printf("Modification time of %s is in the future!\n", file1); exit(1); } my_rename(file1, file2); /* try repeat */ if (!rename(file1, file2)) { printf("repeat rename(%s,%s) worked.. but it shouldn't have\n", file1, file2); exit(1); } /* inode number of file2 should be the same as it was for file1 */ verify_inum(file2, &sb1); /* rename back */ my_rename(file2, file1); verify_inum(file1, &sb1); /* Make a subdir, which will be renamed */ sprintf(subdir, "%s/rename_this_dir", workdir); my_mkdir(subdir); my_stat(subdir, &sb2); /* Test moving a file into a subdir */ sprintf(file2, "%s/file1", subdir); my_rename(file1, file2); verify_inum(file2, &sb1); /* Add in a hard link to spice things up */ sprintf(link, "%s/link", subdir); my_link(file2, link); sprintf(newdir, "%s/newdirname", workdir); my_rename(subdir, newdir); verify_inum(newdir, &sb2); sprintf(file2, "%s/file1", newdir); verify_inum(file2, &sb1); sprintf(link, "%s/newdirname/link", workdir); verify_inum(link, &sb1); /* Test moving up in the tree */ my_rename(file2,file1); verify_inum(file1, &sb1); my_unlink(link); my_rmdir(newdir); }
int main(int argc, char *argv[]) { exit_loop = 0; my_mkdir("/tmp/smartsync"); my_mkdir("/tmp/smartsync/script"); create_shell_file(); //pre_event = -1; //pre_pre_event = -1; create_file_list = create_list_head(); allfolderlist = (Folder *)malloc(sizeof(Folder)); allfolderlist->name = NULL; allfolderlist->next = NULL; allfolderlist_tail = allfolderlist; //create pathlist !!! pathlist = (Folder *)malloc(sizeof(Folder)); pathlist->name = NULL; pathlist->next = NULL; pathlist_tail = pathlist; inotify_fd = open_inotify_fd (); pthread_mutex_init(&mutex_allfolderlist, NULL); pthread_mutex_init(&mutex_inotify_fd, NULL); pthread_mutex_init(&mutex_pathlist, NULL); dragfolder_wd = 0; sigset_t bset,oset; pthread_t sig_thread; sigemptyset(&bset); sigaddset(&bset,SIGTERM); if( pthread_sigmask(SIG_BLOCK,&bset,&oset) == -1) printf("!! Set pthread mask failed\n"); if( pthread_create(&sig_thread,NULL,(void *)sigmgr_thread,NULL) != 0) { printf("thread creation failder\n"); exit(-1); } pthread_t newthid1,newthid2; if( pthread_create(&newthid1,NULL,(void *)watch_socket,NULL) != 0) { printf("thread creation failder\n"); exit(1); } if( pthread_create(&newthid2,NULL,(void *)watch_folder,NULL) != 0) { printf("thread creation failder\n"); exit(1); } //sleep(1); pthread_join(newthid2,NULL); close_inotify_fd (inotify_fd); return 0; }
int write_file() { if (called_count == 0) goto add_timer; time_t timep; struct tm *p; time(&timep); timep = timep - (timep % (data_store_time * 60)); p = localtime(&timep); char path_today_cdn[1024]; char path_today_now_cdn[1024]; char path_today_now_cdn_tmp[1024]; char path_cdn_special[1024]; snprintf(path_today_cdn, sizeof(path_today_cdn),"%s/ver_%03d/cdn/%4d-%02d-%02d", data_store_path, current_version, 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday); snprintf(path_today_now_cdn, sizeof(path_today_now_cdn), "%s/META-%4d-%02d-%02d-%02d-%02d-%02d", path_today_cdn, 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday,p->tm_hour, p->tm_min, p->tm_sec); snprintf(path_today_now_cdn_tmp, sizeof(path_today_now_cdn_tmp), "%s/tmp.%4d-%02d-%02d-%02d-%02d-%02d", path_today_cdn, 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); snprintf(path_cdn_special, sizeof(path_cdn_special),"%s/ver_%03d/cdn_special.dat", data_store_path, current_version); if (my_mkdir(path_today_cdn) == -1) return -1; int fd_cdn = open(path_today_now_cdn, O_RDWR | O_CREAT | O_APPEND, 00666); int fd_cdn_special = open(path_cdn_special, O_RDWR | O_CREAT | O_APPEND, 00666); char path_today_url[1024]; char path_today_now_url[1024]; char path_today_now_url_tmp[1024]; char path_url_special[1024]; snprintf(path_today_url, sizeof(path_today_url),"%s/ver_%03d/url/%4d-%02d-%02d", data_store_path, current_version, 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday); snprintf(path_today_now_url, sizeof(path_today_now_url), "%s/META-%4d-%02d-%02d-%02d-%02d-%02d", path_today_url, 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); snprintf(path_today_now_url_tmp, sizeof(path_today_now_url_tmp), "%s/tmp.%4d-%02d-%02d-%02d-%02d-%02d", path_today_url, 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); snprintf(path_url_special, sizeof(path_url_special),"%s/ver_%03d/url_special.dat", data_store_path, current_version); if (my_mkdir(path_today_url) == -1) return -1; int fd_url = open(path_today_now_url, O_RDWR | O_CREAT | O_APPEND, 00666); int fd_url_special = open(path_url_special, O_RDWR | O_CREAT | O_APPEND, 00666); int tag = g_buffer_tag; //占用当前缓冲区 g_buffer_tag ^= 1; //切换缓冲区 使得recv函数的数据写到另一个缓冲区. fcgi_store_t *record = (fcgi_store_t*)g_buffer[tag]; int i; int data_len = sizeof(fcgi_store_t);; for (i = 0; i < sum_data_in_mem[tag]; i++) { switch (record->type) { case proto_fcgi_cdn_report: { write(fd_cdn, record, data_len); if (record->special_flag == 1) { write(fd_cdn_special, record, data_len); } } break; case proto_fcgi_url_report: { write(fd_url, record, data_len); if (record->special_flag == 1) { write(fd_url_special, record, data_len); } } break; default: break; }//switch record ++; }//for char zero[1024]; memset(zero, 0x0, sizeof(zero)); write(fd_cdn, zero, data_len); //cdn分钟文件之间全0隔开 write(fd_url, zero, data_len); //url分钟文件之间全0隔开 close(fd_cdn); close(fd_url); close(fd_cdn_special); close(fd_url_special); //rename(path_today_now_cdn_tmp, path_today_now_cdn); //rename(path_today_now_url_tmp, path_today_now_url); g_buffer_ptr[tag] = g_buffer[tag]; sum_data_in_mem[tag] = 0; add_timer: called_count++; ADD_TIMER_EVENT(&g_timer, write_file, NULL, get_now_tv()->tv_sec + 60 - get_now_tv()->tv_sec % 60); return 0; }
void test_my_write() { printf("\ntest_my_write:\n"); if (my_mkdir("/foo") < 0) { printf("Failed at making directory /foo\n"); exit(1); } if (my_mkdir("/foo/bar") < 0) { printf("Failed at making directory /foo/bar\n"); exit(1); } int fd; if ((fd = my_creat("/foo/bar/test.txt")) < 0) { printf("Failed at creating file /foo/bar/test.txt\n"); exit(1); } int block_num = get_associated_block_num(fd); printf("Created file at block number %d\n", block_num); char string[101] = "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij\0"; if (DEBUG) { printf("Writing string of length 100\n"); } if (my_write(fd, string, 100) < 0) { printf("Failed to write string to file /foo/bar/test.txt\n"); exit(1); } char buffer[1024]; if (read_block(block_num, buffer) < 0) { printf("Error reading block #%d\n", block_num); exit(1); } short bytesAllocated; memcpy(&bytesAllocated, buffer + 1 + sizeof(int), sizeof(bytesAllocated)); if (DEBUG) { printf("bytes allocated: %d\n", bytesAllocated); } char * buffer_ptr = buffer + 8; char data[101]; strncpy(data, buffer_ptr, 100); data[100] = '\0'; if (strcmp(data, string) != 0) { printf("Error in reading back out data\n"); exit(1); } if (DEBUG) { printf("Closing file %d\n", fd); } if (my_close(fd) < 0) { printf("Failed to close file %d\n", fd); exit(1); } if ((fd = my_open("/foo/bar/test.txt")) < 0) { printf("Failed to open file /foo/bar/test.txt\n"); exit(1); } if (DEBUG) { printf("Opened file %d\n", fd); } char string2[50] = "jihgfedcbajihgfedcbajihgfedcbajihgfedcbajihgfedcba"; if (DEBUG) { printf("Writing string of length 50\n"); } strncpy(string, string2, 50); if (my_write(fd, string2, 50) < 0) { printf("Failed to write string2 to /foo/bar/test.txt\n"); exit(1); } block_num = get_associated_block_num(fd); if (read_block(block_num, buffer) < 0) { printf("Error reading block #%d\n", block_num); exit(1); } memcpy(&bytesAllocated, buffer + 1 + sizeof(int), sizeof(bytesAllocated)); if (DEBUG) { printf("bytes allocated: %d\n", bytesAllocated); } buffer_ptr = buffer + HEADER_SIZE; memset(data, '\0', strlen(data)); strncpy(data, buffer_ptr, 101); if (strcmp(data, string) != 0) { printf("Error in reading back out data\n"); exit(1); } if (DEBUG) { printf("Closing file %d\n", fd); } if (my_close(fd) < 0) { printf("Failed to close file %d\n", fd); exit(1); } if ((fd = my_open("/foo/bar/test.txt")) < 0) { printf("Failed to open file /foo/bar/test.txt\n"); exit(1); } if (DEBUG) { printf("Opened file %d\n", fd); } block_num = get_associated_block_num(fd); char alphabet[26] = "abcdefghijlkmnopqrstuvwxyz"; char longString[1501]; int i; for (i = 0; i < 1500; i++) { longString[i] = alphabet[(i % 26)]; } longString[1500] = '\0'; if (DEBUG) { printf("Writing string of length 1500\n"); } if (my_write(fd, longString, 1500) < 0) { printf("Failed to write string2 to /foo/bar/test.txt\n"); exit(1); } if (read_block(block_num, buffer) < 0) { printf("Error reading block #%d\n", block_num); exit(1); } memcpy(&bytesAllocated, buffer + 1 + sizeof(int), sizeof(bytesAllocated)); if (DEBUG) { printf("bytes allocated in first block excluding header: %d\n", (bytesAllocated - HEADER_SIZE)); } if (bytesAllocated != 1024) { printf("Error allocated %d bytes\n", bytesAllocated); } int next_block; memcpy(&next_block, buffer + 1, sizeof(next_block)); if (next_block == 0) { printf("Didn't properly create a new block.\n"); exit(1); } else { printf("Created new file block at block %d, when writing\n", next_block); } char new_buffer[1024]; if (read_block(next_block, new_buffer) < 0) { printf("Error reading block #%d\n", next_block); exit(1); } short newBytesAllocated; memcpy(&newBytesAllocated, new_buffer + 1 + sizeof(int), sizeof(newBytesAllocated)); if (DEBUG) { printf("Number of bytes allocated in second block excluding header: %d\n", (newBytesAllocated - HEADER_SIZE)); printf("Total number of bytes allocated from string of length 1500: %d\n", (bytesAllocated + newBytesAllocated - (2 * HEADER_SIZE))); } char longData[1501]; buffer_ptr = buffer + HEADER_SIZE; strncpy(longData, buffer_ptr, (bytesAllocated - HEADER_SIZE)); char * longData_ptr = longData + (bytesAllocated - HEADER_SIZE); char * new_buffer_ptr = new_buffer + HEADER_SIZE; strncpy(longData_ptr, new_buffer_ptr, (newBytesAllocated - HEADER_SIZE)); longData[1500] = '\0'; if (strcmp(longString, longData) != 0) { printf("Error in writing data\n"); exit(1); } char longerString[1601]; for (i = 0; i < 1600; i++) { if (i < 1500) { longerString[i] = longString[i]; } else { longerString[i] = string[(i - 1500)]; } } longerString[1600] = '\0'; if (DEBUG) { printf("Appending string of length 100 to open file %d\n", fd); } if (my_write(fd, string, 100) < 0) { printf("Failed to write string2 to /foo/bar/test.txt\n"); exit(1); } if (read_block(block_num, buffer) < 0) { printf("Error reading block #%d\n", block_num); exit(1); } buffer_ptr = buffer + 1; memcpy(&next_block, buffer_ptr, sizeof(next_block)); if (read_block(next_block, buffer) < 0) { printf("Error reading block #%d\n", block_num); exit(1); } buffer_ptr = buffer + 1 + sizeof(next_block); memcpy(&bytesAllocated, buffer_ptr, sizeof(bytesAllocated)); if (bytesAllocated != (newBytesAllocated + 100)) { printf("Error not enough bytes allocated\n"); exit(1); } if (DEBUG) { printf("bytes allocated in block appended too excluding header: %d\n", (bytesAllocated - HEADER_SIZE)); } buffer_ptr = buffer + newBytesAllocated; memset(data, '\0', 100); strncpy(data, buffer_ptr, 100); data[100] = '\0'; if (strcmp(data, string) != 0) { printf("Error in writing to already written to file that wasn't closed.\n"); exit(1); } if (DEBUG) { printf("Recursively removing directory /foo and all it's contents\n"); } if (my_rmdir("/foo") < 0) { printf("Failed at removing directory /foo\n"); exit(1); } block_num = get_associated_block_num(fd); if (block_num != 0) { printf("Error file still seen as open\n"); exit(1); } printf("Recursively deleted directory /foo\n"); printf("test_my_write: PASSED\n"); }
static int create_sys_files(struct languages *lang_head, struct errors *error_head, uint row_count) { FILE *to; uint csnum= 0, length, i, row_nr; uchar head[32]; char outfile[FN_REFLEN], *outfile_end; long start_pos; struct message *tmp; struct languages *tmp_lang; struct errors *tmp_error; MY_STAT stat_info; DBUG_ENTER("create_sys_files"); /* going over all languages and assembling corresponding error messages */ for (tmp_lang= lang_head; tmp_lang; tmp_lang= tmp_lang->next_lang) { /* setting charset name */ if (!(csnum= get_charset_number(tmp_lang->charset, MY_CS_PRIMARY))) { fprintf(stderr, "Unknown charset '%s' in '%s'\n", tmp_lang->charset, TXTFILE); DBUG_RETURN(1); } outfile_end= strxmov(outfile, DATADIRECTORY, tmp_lang->lang_long_name, NullS); if (!my_stat(outfile, &stat_info,MYF(0))) { if (my_mkdir(outfile, 0777,MYF(0)) < 0) { fprintf(stderr, "Can't create output directory for %s\n", outfile); DBUG_RETURN(1); } } strxmov(outfile_end, FN_ROOTDIR, OUTFILE, NullS); if (!(to= my_fopen(outfile, O_WRONLY | FILE_BINARY, MYF(MY_WME)))) DBUG_RETURN(1); /* 4 is for 4 bytes to store row position / error message */ start_pos= (long) (HEADER_LENGTH + row_count * 4); fseek(to, start_pos, 0); row_nr= 0; for (tmp_error= error_head; tmp_error; tmp_error= tmp_error->next_error) { /* dealing with messages */ tmp= find_message(tmp_error, tmp_lang->lang_short_name, FALSE); if (!tmp) { fprintf(stderr, "Did not find message for %s neither in %s nor in default " "language\n", tmp_error->er_name, tmp_lang->lang_short_name); goto err; } if (copy_rows(to, tmp->text, row_nr, start_pos)) { fprintf(stderr, "Failed to copy rows to %s\n", outfile); goto err; } row_nr++; } /* continue with header of the errmsg.sys file */ length= ftell(to) - HEADER_LENGTH - row_count * 4; memset(head, 0, HEADER_LENGTH); memmove(head, file_head, 4); head[4]= 1; int4store(head + 6, length); int4store(head + 10, row_count); head[30]= csnum; my_fseek(to, 0l, MY_SEEK_SET, MYF(0)); if (my_fwrite(to, (uchar*) head, HEADER_LENGTH, MYF(MY_WME | MY_FNABP))) goto err; for (i= 0; i < row_count; i++) { int4store(head, file_pos[i]); if (my_fwrite(to, (uchar*) head, 4, MYF(MY_WME | MY_FNABP))) goto err; } my_fclose(to, MYF(0)); } DBUG_RETURN(0); err: my_fclose(to, MYF(0)); DBUG_RETURN(1); }
int main( int, char *[] ) { boost::system::error_code ec; // Library 1 tests: ec = my_mkdir( "/no-such-file-or-directory/will-not-succeed" ); std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == boost::system::errc::no_such_file_or_directory ); BOOST_TEST( ec.category() == boost::system::system_category() ); // Library 2 tests: ec = my_remove( "/no-such-file-or-directory" ); std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == boost::system::errc::no_such_file_or_directory ); BOOST_TEST( ec.category() == boost::system::generic_category() ); // Library 3 tests: ec = boost::lib3::boo_boo; std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == boost::lib3::boo_boo ); BOOST_TEST( ec.value() == boost::lib3::boo_boo ); BOOST_TEST( ec.category() == boost::lib3::lib3_error_category ); BOOST_TEST( ec == boost::system::errc::io_error ); boost::system::error_code ec3( boost::lib3::boo_boo+100, boost::lib3::lib3_error_category ); BOOST_TEST( ec3.category() == boost::lib3::lib3_error_category ); BOOST_TEST( ec3.default_error_condition().category() == boost::lib3::lib3_error_category ); // Library 4 tests: ec = lib4::boo_boo; std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == lib4::boo_boo ); BOOST_TEST( ec.value() == lib4::boo_boo.value() ); BOOST_TEST( ec.category() == lib4::lib4_error_category ); BOOST_TEST( ec == boost::system::errc::io_error ); boost::system::error_code ec4( lib4::boo_boo.value()+100, lib4::lib4_error_category ); BOOST_TEST( ec4.default_error_condition().category() == lib4::lib4_error_category ); // Test 3 //test3::run(); return ::boost::report_errors(); }
int vrfydir(const struct periodstruct *per1, const char *addr, const char *site, const char *us, const char *form) { FILE *fp_ou; int num=1, count=0; char wdir[MAXLEN]; char dirname2[MAXLEN]; int y1, y2; int m1, m2; int d1, d2; int wlen, wlen2; time_t curtime; struct tm *loctm; strcpy(wdir,outdir); wlen=strlen(wdir); y1=per1->start.tm_year+1900; y2=per1->end.tm_year+1900; m1=per1->start.tm_mon+1; m2=per1->end.tm_mon+1; d1=per1->start.tm_mday; d2=per1->end.tm_mday; if(IndexTree == INDEX_TREE_DATE) { wlen+=sprintf(wdir+wlen,"%04d",y1); if(y1!=y2) wlen+=sprintf(wdir+wlen,"-%04d",y2); if(access(wdir, R_OK) != 0) my_mkdir(wdir); wlen+=sprintf(wdir+wlen,"/%02d",m1); if(m1 != m2) wlen+=sprintf(wdir+wlen,"-%02d",m2); if(access(wdir, R_OK) != 0) my_mkdir(wdir); wlen+=sprintf(wdir+wlen,"/%02d",d1); if(d1!=d2) wlen+=sprintf(wdir+wlen,"-%02d",d2); } else { if(df[0] == 'u') { wlen=snprintf(wdir+wlen,sizeof(wdir)-wlen,"%04d%s%02d-%04d%s%02d",y1, conv_month_name(m1),d1,y2,conv_month_name(m2),d2); } else if(df[0] == 'e') { wlen=snprintf(wdir+wlen,sizeof(wdir)-wlen,"%02d%s%04d-%02d%s%04d",d1, conv_month_name(m1),y1,d2,conv_month_name(m2),y2); } else if(df[0] == 'w') { wlen2=strftime(wdir+wlen, sizeof(wdir)-wlen, "%Y.%U", &per1->start); if (wlen2==0) return(-1); wlen+=wlen2; } } if(us[0] != '\0') { struct userinfostruct *uinfo=userinfo_find_from_id(us); if (uinfo) { strcat(wdir,"-"); strcat(wdir,uinfo->filename); } } if(addr[0] != '\0') { strcat(wdir,"-"); strcat(wdir,addr); } if(site[0] != '\0') { strcat(wdir,"-"); strcat(wdir,site); } strcpy(outdirname,wdir); if(IndexTree != INDEX_TREE_DATE) { if(!OverwriteReport) { while(num) { if(access(wdir,R_OK) == 0) { sprintf(wdir,"%s.%d",outdirname,num); num++; count++; } else break; } if(count > 0) { if(debug) debuga(_("File %s already exists, moved to %s\n"),outdirname,wdir); rename(outdirname,wdir); } } else { if(access(outdirname,R_OK) == 0) { unlinkdir(outdirname,1); } } my_mkdir(outdirname); } else { strcpy(dirname2,wdir); if(!OverwriteReport) { while(num) { if(access(wdir,R_OK) == 0) { sprintf(wdir,"%s.%d",dirname2,num); num++; count++; } else break; } if(count > 0) { if(debug) debuga(_("File %s already exists, moved to %s\n"),dirname2,wdir); rename(dirname2,wdir); strcpy(dirname2,wdir); } } else { if(access(wdir,R_OK) == 0) { unlinkdir(wdir,1); } } if(access(wdir, R_OK) != 0) my_mkdir(wdir); } strcpy(dirname2,wdir); sprintf(wdir,"%s/sarg-date",outdirname); if ((fp_ou = fopen(wdir, "wt")) == 0) { debuga(_("cannot open %s for writing\n"),wdir); perror("SARG:"); exit(EXIT_FAILURE); } time(&curtime); //strftime(wdir,sizeof(wdir),"%a %b %d %H:%M:%S %Z %Y",localtime(&curtime)); loctm=localtime(&curtime); strftime(wdir,sizeof(wdir),"%Y-%m-%d %H:%M:%S",loctm); if (fprintf(fp_ou,"%s %d\n",wdir,loctm->tm_isdst)<0) { debuga(_("Failed to write the date in %s\n"),wdir); perror("SARG:"); exit(EXIT_FAILURE); } if (fclose(fp_ou)==EOF) { debuga(_("Failed to write the date in %s\n"),wdir); perror("SARG:"); exit(EXIT_FAILURE); } copy_images(); return(0); }
static int unpack (const TCHAR *src, const TCHAR *filename, const TCHAR *dst, int out, int all, int level) { struct zdirectory *h; struct zvolume *zv; int ret; uae_u8 *b; int size; TCHAR fn[MAX_DPATH]; ret = 0; zv = zfile_fopen_archive_root (src, ZFD_ALL); if (zv == NULL) { geterror(); _tprintf (_T("Couldn't open archive '%s'\n"), src); return 0; } h = zfile_opendir_archive (src); if (!h) { geterror(); _tprintf (_T("Couldn't open directory '%s'\n"), src); return 0; } while (zfile_readdir_archive (h, fn)) { if (all || !_tcsicmp (filename, fn)) { TCHAR tmp[MAX_DPATH]; struct zfile *s, *d; struct mystat st; found = 1; _tcscpy (tmp, src); _tcscat (tmp, sep); _tcscat (tmp, fn); if (!zfile_stat_archive (tmp, &st)) { _tprintf (_T("Couldn't stat '%s'\n"), tmp); continue; } if (dst == NULL || all) dst = fn; if (st.mode) { if (all > 0) continue; if (all < 0) { TCHAR oldcur[MAX_DPATH]; my_mkdir (fn); my_setcurrentdir (fn, oldcur); unpack (tmp, fn, dst, out, all, 1); my_setcurrentdir (oldcur, NULL); setdate (dst, st.mtime.tv_sec); continue; } _tprintf (_T("Directory extraction not yet supported\n")); return 0; } s = zfile_open_archive (tmp, ZFD_ARCHIVE | ZFD_NORECURSE); if (!s) { geterror(); _tprintf (_T("Couldn't open '%s' for reading\n"), src); continue; } zfile_fseek (s, 0, SEEK_END); size = zfile_ftell (s); zfile_fseek (s, 0, SEEK_SET); b = xcalloc (uae_u8, size); if (b) { if (zfile_fread (b, size, 1, s) == 1) { if (out) { _tprintf (_T("\n")); fwrite (b, size, 1, stdout); } else { d = zfile_fopen (dst, _T("wb"), 0); if (d) { if (zfile_fwrite (b, size, 1, d) == 1) { ret = 1; _tprintf (_T("%s extracted, %d bytes\n"), dst, size); } zfile_fclose (d); setdate (dst, st.mtime.tv_sec); } } } xfree (b); } zfile_fclose (s); if (!all) break; } } geterror (); if (!found && !level) { if (filename[0]) _tprintf (_T("'%s' not found\n"), filename); else _tprintf (_T("nothing extracted\n")); } return ret; }
int main ( int argc, char **argv, char **env ) { int rc, i; char *stmpdir; embedded_file_t *emb_file; char *my_file; char *my_perl; char *my_prog; char buf[20]; /* must be large enough to hold "PAR_ARGV_###" */ #ifdef WIN32 typedef BOOL (WINAPI *pALLOW)(DWORD); HINSTANCE hinstLib; pALLOW ProcAdd; #ifndef ASFW_ANY #define ASFW_ANY -1 #endif #endif #define DIE exit(255) par_init_env(); stmpdir = par_mktmpdir( argv ); if ( !stmpdir ) DIE; /* error message has already been printed */ rc = my_mkdir(stmpdir, 0700); if ( rc == -1 && errno != EEXIST) { fprintf(stderr, "%s: creation of private cache subdirectory %s failed (errno= %i)\n", argv[0], stmpdir, errno); DIE; } /* extract embedded_files[0] (i.e. the custom Perl interpreter) * into stmpdir (but under the same basename as argv[0]) */ my_prog = par_findprog(argv[0], strdup(par_getenv("PATH"))); rc = extract_embedded_file(embedded_files, par_basename(my_prog), stmpdir, &my_perl); if (rc == EXTRACT_FAIL) { fprintf(stderr, "%s: extraction of %s (custom Perl interpreter) failed (errno=%i)\n", argv[0], my_perl, errno); DIE; } if (rc == EXTRACT_OK) /* i.e. file didn't already exist */ { #ifdef __hpux { /* HPUX will only honour SHLIB_PATH if the executable is specially marked */ char *chatr_cmd = malloc(strlen(my_perl) + 200); sprintf(chatr_cmd, "/usr/bin/chatr +s enable %s > /dev/null", my_perl); system(chatr_cmd); } #endif #ifdef WIN32 { /* copy IMAGE_OPTIONAL_HEADER.Subsystem (GUI vs console) * from this executable to the just extracted my_perl */ int fd; WORD subsystem; fd = open(my_prog, O_RDONLY | OPEN_O_BINARY, 0755); ASSERT(fd != -1, "open my_prog"); seek_to_subsystem(fd); read(fd, &subsystem, 2); // CHECK == 2 close(fd); // CHECK != -1 fd = open(my_perl, O_RDWR | OPEN_O_BINARY, 0755); ASSERT(fd != -1, "open my_perl"); seek_to_subsystem(fd); write(fd, &subsystem, 2); // CHECK == 2 close(fd); // CHECK != -1 } #endif } /* extract the rest of embedded_files into stmpdir */ emb_file = embedded_files + 1; while (emb_file->name) { if (extract_embedded_file(emb_file, emb_file->name, stmpdir, &my_file) == EXTRACT_FAIL) { fprintf(stderr, "%s: extraction of %s failed (errno=%i)\n", argv[0], my_file, errno); DIE; } emb_file++; } /* save original argv[] into environment variables PAR_ARGV_# */ sprintf(buf, "%i", argc); par_setenv("PAR_ARGC", buf); for (i = 0; i < argc; i++) { sprintf(buf, "PAR_ARGV_%i", i); par_unsetenv(buf); par_setenv(buf, argv[i]); } /* finally spawn the custom Perl interpreter */ #ifdef WIN32 hinstLib = LoadLibrary("user32"); if (hinstLib != NULL) { ProcAdd = (pALLOW) GetProcAddress(hinstLib, "AllowSetForegroundWindow"); if (ProcAdd != NULL) { (ProcAdd)(ASFW_ANY); } } par_setenv("PAR_SPAWNED", "1"); rc = spawnvpe(P_WAIT, my_perl, (const char* const*)argv, (const char* const*)environ); par_cleanup(stmpdir); exit(rc); #else execvp(my_perl, argv); DIE; #endif }