int s3fs_rename(const char *from, const char *to) { #ifdef DEBUG syslog(LOG_INFO, "rename[%s] -> [%s]", from, to); #endif try { Transaction t; // move the file over t.path = from; // if the file is a directory, rename_file will return the // Filecache object for the source so we can delete it at the end // we are responsible for releasing it, so hand it to our transaction t.file = rename_file(from, to, true); if (t.file) { // this is a directory, so rename all descendents Filecache::sync(); std::string marker; bool moretocome = true; while (moretocome) { stringlist entries; moretocome = S3request::get_directory(from, marker, entries, MAX_KEYS_PER_DIR_REQUEST, true); for (size_t i = 0; i < entries.size(); i++) { std::string src(from); src += "/" + entries[i]; std::string tgt(to); tgt += "/" + entries[i]; #ifdef DEBUG syslog(LOG_INFO, "rename[%s] -> [%s]", src.c_str(), tgt.c_str()); #endif // move the file over rename_file(src, tgt, false); } } // move any files inside the directory before removing the source t.file->deleted = true; Filecache::sync(); } return 0; } catch (int e) { syslog(LOG_INFO, "rename[%s] -> [%s]: %s", from, to, strerror(e)); return e; } }
/* * Rename a file or directory. */ int vboxfs_rename(char *opath, char *npath) { int r; if ((r = rename_file(opath, npath, FALSE /*dir*/)) != EISDIR) return r; return rename_file(opath, npath, TRUE /*dir*/); }
void IPC::send_message(const string recipient, const string message_head, const string message_body) { vector<string> file_name_vec = list_files_in_directory(ipc_path); bool found = true; int file_count = 0; while (found) { found = false; for (string file_name_current : file_name_vec) if (file_name_current == recipient + to_string(file_count)) { found = true; ++file_count; break; } } static int sent_count = 0; const string path_old = ipc_path + "\\s" + self_name + to_string(sent_count); const string path_new = ipc_path + "\\" + recipient + to_string(file_count); write_string_to_file(path_old, message_head + "!" + message_body); rename_file(path_old, path_new); ++sent_count; COUT << "message sent: " << recipient << " " << message_head << " " << message_body << endl; }
void FileImpl::renameToImpl(const std::string& path) { poco_assert (!_path.empty()); POCO_DESCRIPTOR_STRING(oldNameDsc, _path); POCO_DESCRIPTOR_STRING(newNameDsc, path); int res; if ((res = lib$rename_file(&oldNameDsc, &newNameDsc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) != 1) { switch (res & 0x0FFFFFFF) { case RMS$_FNF: throw FileNotFoundException(_path); case RMS$_DEV: case RMS$_DNF: throw PathNotFoundException(_path); case RMS$_SYN: throw PathSyntaxException(path); case RMS$_RMV: throw FileAccessDeniedException(_path); case RMS$_PRV: throw FileAccessDeniedException("insufficient privileges", _path); default: throw FileException(path); } } }
void torrent_handle::rename_file(int index, fs::wpath const& new_name) const { INVARIANT_CHECK; std::string utf8; wchar_utf8(new_name.string(), utf8); TORRENT_FORWARD(rename_file(index, utf8)); }
static void rotate_logs(void) { FILE *new_fd = NULL; log_count = 0; // Move present log file to backup file // RTV_PRT("Rotating log files...\n"); if ( rename_file(log_fn, log_backup_fn) == -1 ) { RTV_ERRLOG("Rotate LogFile: backup rename error: %s\n errno=%d=>%s", log_fn, errno, strerror(errno)); } //open a new log file // new_fd = fopen(log_fn, "w"); if ( new_fd == NULL ) { RTV_ERRLOG("Rotate LogFile fopen error: %s\n errno=%d=>%s", log_fn, errno, strerror(errno)); rtv_globals.log_fd = stderr; log_to_file = 0; return; } fclose(rtv_globals.log_fd); rtv_globals.log_fd = new_fd; return; }
void reset_newsrc( void) { FILE *fp; FILE *newfp; char *line; int sub; long i; if (!no_write && (newfp = fopen(newnewsrc, "w" FOPEN_OPTS)) != NULL) { #ifndef M_OS2 if (newsrc_mode) fchmod(fileno(newfp), newsrc_mode); #endif /* !M_OS2 */ if ((fp = fopen(newsrc, "r")) != NULL) { while ((line = tin_fgets(fp, FALSE)) != NULL) { (void) parse_newsrc_line(line, &sub); fprintf(newfp, "%s%c\n", line, sub); } fclose(fp); } if (ferror(newfp) || fclose(newfp)) { error_message(_(txt_filesystem_full), NEWSRC_FILE); unlink(newnewsrc); } else rename_file(newnewsrc, newsrc); } for (i = 0; i < selmenu.max; i++) set_default_bitmap(&active[my_group[i]]); }
/*\ |*| Rename a file so it's not in the way |*| Append '.bad' because I assume a file that's in the way |*| is a corrupt version. \*/ int move_away(u16 *file, const u8 *ext) { u16 *fn; int l, i; if (!file_exists(file)) return 0; if (!cmd.move) return -1; for (i = 0; file[i]; i++) ; l = i + strlen(ext); NEW(fn, l + 1); COPY(fn, file, i); for (; i <= l; i++) fn[i] = *ext++; i = 0; while (file_exists(fn)) { if (i > 99) return -1; fn[l-2] = '0' + (i / 10); fn[l-1] = '0' + (i % 10); i++; } i = rename_file(file, fn); free(fn); return i; }
/** The main(). It parses the command line, setup the parms, ask the scheduler for signal to proceed, and then starts skysim to do sky coverage. */ int main(int argc, const char *argv[]){ dirstart=mygetcwd(); char *scmd=argv2str(argc, argv, " "); ARG_S* arg=parse_args(argc,argv); /*In detach mode send to background and disable drawing*/ if(arg->detach){ daemonize(); }else{ redirect(); } info2("%s\n", scmd); info2("Output folder is '%s'. %d threads\n",arg->dirout, arg->nthread); skyc_version(); /*register signal handler */ register_signal_handler(skyc_signal_handler); /* Ask job scheduler for permission to proceed. If no CPUs are available, will block until ones are available. if arg->force==1, will run immediately. */ scheduler_start(scmd,arg->nthread,0,!arg->force); /*setting up parameters before asking scheduler to check for any errors. */ dirsetup=stradd("setup",NULL); PARMS_S * parms=setup_parms(arg); if(parms->skyc.dbg){ mymkdir("%s",dirsetup); } if(!arg->force){ info2("Waiting start signal from the scheduler ...\n"); /*Failed to wait. fall back to own checking.*/ int count=0; while(scheduler_wait()&& count<60){ warning_time("failed to get reply from scheduler. retry\n"); sleep(10); count++; scheduler_start(scmd,arg->nthread,0,!arg->force); } if(count>=60){ warning_time("fall back to own checker\n"); wait_cpu(arg->nthread); } } info2("Simulation started at %s in %s.\n",myasctime(),myhostname()); free(scmd); free(arg->dirout); free(arg); THREAD_POOL_INIT(parms->skyc.nthread); /*Loads the main software*/ OMPTASK_SINGLE skysim(parms); free_parms(parms); free(dirsetup); free(dirstart); rename_file(0); scheduler_finish(0); info2("End:\t%.2f MiB\n",get_job_mem()/1024.); info2("Simulation finished at %s in %s.\n",myasctime(),myhostname()); return 0; }
/* * Read in the users newsrc file and write a new file with all the changes * changes from the current session. If this works, replace the original * newsrc file. * Returns < 0 on error * >=0 number of lines written */ signed long int write_newsrc( void) { FILE *fp_ip; FILE *fp_op; char *line; signed long int tot = 0L; struct stat note_stat_newsrc; t_bool write_ok = FALSE; if (no_write) return 0L; if ((fp_ip = fopen(newsrc, "r")) == NULL) return -1L; /* can't open newsrc */ /* get size of original newsrc */ fstat(fileno(fp_ip), ¬e_stat_newsrc); if (!note_stat_newsrc.st_size) { fclose(fp_ip); return 0L; /* newsrc is empty */ } if ((fp_op = fopen(newnewsrc, "w" FOPEN_OPTS)) != NULL) { #ifndef M_OS2 if (newsrc_mode) fchmod(fileno(fp_op), newsrc_mode); #endif /* !M_OS2 */ while ((line = tin_fgets(fp_ip, FALSE)) != NULL) tot += write_newsrc_line(fp_op, line); /* * Don't rename if either fclose() fails or ferror() is set */ if (ferror(fp_op) || fclose(fp_op)) { error_message(_(txt_filesystem_full), NEWSRC_FILE); unlink(newnewsrc); } else write_ok = TRUE; } fclose(fp_ip); if (tot < 1) { error_message(_(txt_newsrc_nogroups)); return 0L; /* So we don't get prompted to try again */ } if (write_ok) rename_file(newnewsrc, newsrc); return tot; }
void rename_file_ok(GtkFileChooser *file_selection) { GString *filename; // Extract filename from the file chooser dialog gchar *fileuri=gtk_file_chooser_get_uri(file_selection); filename = g_string_new(fileuri); g_free(fileuri); GFile *file = get_gfile_from_filename(filename->str); if (g_file_query_exists (file,NULL)) { gint result = yes_no_dialog (_("gPHPEdit"), _("This file already exists, are you sure you want to overwrite it?")); if (result==GTK_RESPONSE_YES) { rename_file(filename); } } else { rename_file(filename); } g_object_unref(file); g_string_free(filename, TRUE); }
int rotate_log(struct rotator *rr,char *filename) { char *dir,*base,*oldname,*newname; DIR *dirh; struct dirent des,*de; struct array *names; struct assoc *changes,*orders; int order,i,n; dirbasename(filename,&dir,&base); log_debug(("Rotating in '%s'",dir)); dirh = opendir(dir); if(!dirh) { log_error(("Could not rotate log file")); return 1; } names = array_create(type_free,0); changes = assoc_create(0,0,type_free,0); orders = assoc_create(0,0,type_free,0); while(1) { if(readdir_r(dirh,&des,&de)) { log_error(("Problem reading directory during log rotation")); break; } if(!de) { break; } order = matching_file(rr,filename,de->d_name,&newname); if(order == MATCH_IGNORE) { continue; } if(order == MATCH_DELETE) { log_debug(("delete %s",de->d_name)); unlink(de->d_name); } else { oldname = strdup(de->d_name); array_insert(names,oldname); assoc_set(changes,oldname,newname); assoc_set(orders,oldname,make_int(order)); } } if(closedir(dirh)) { log_error(("Could not closedir during log rotation!")); /* But continue: what else to do? */ } array_sort(names,sort_names,orders); n = array_length(names); for(i=0;i<n;i++) { oldname = array_index(names,i); newname = assoc_lookup(changes,oldname); log_warn(("name=%s -> %s",oldname,newname)); rename_file(rr,dir,oldname,newname); } assoc_release(changes); assoc_release(orders); array_release(names); free(dir); free(base); return 0; }
void cp(char * filename, char * path) { int i, name_length, type, ret, j; filename[str_len(filename) - 1] = 0; iNode * path_inode = current; path_inode = parser_path(path, path_inode); iNode * filename_inode = current; filename_inode = parser_path(filename, filename_inode); if(filename_inode->gid < currentUsr.group) { printf("\nCan not copy '%s'. Permission denied.", filename); return ; } if(filename_inode == NULL) { printf("\nCan not copy '%s'. File doesn't exist.", filename); return ; } if(path_inode == NULL) { name_length = str_len(path); for(i = 0; i < name_length; i++) if(path[i] == '/') { printf("\nCan not copy '%s' to '%s'. Directory doesn't exist.", filename, path); return; } rename_file(filename_inode->iNode_number, path); return ; } int init_block = current->data.direct_blocks[0]; directoryEntry * dr = (directoryEntry*)calloc(64 * 96, 1); read_disk(0, init_block, dr, (BLOCK_SIZE * 12), 0); for(i = 1; i < 96; i++){ if( strcmp(filename, dr[i].name) == 1){ type = dr[i].type; break; } } if(type == FILE) { cp_file(filename, filename_inode, path_inode); } else if(type == DIRECTORY) { recursive_cp(filename, filename_inode, path_inode); } return ; }
/** Write the access.cnf file. * Writes out the access.cnf file from the linked list */ void write_access_file(void) { FILE *fp; char tmpf[BUFFER_LEN]; struct access *ap; acsflag *c; snprintf(tmpf, BUFFER_LEN, "%s.tmp", ACCESS_FILE); /* Be sure we have a file descriptor */ release_fd(); fp = fopen(tmpf, FOPEN_WRITE); if (!fp) { do_log(LT_ERR, GOD, GOD, "Unable to open %s.", tmpf); } else { for (ap = access_top; ap; ap = ap->next) { if (strcmp(ap->host, "@sitelock") == 0) { fprintf(fp, "@sitelock\n"); continue; } fprintf(fp, "%s %d ", ap->host, ap->who); switch (ap->can) { case ACS_SITELOCK: break; case ACS_DEFAULT: fprintf(fp, "DEFAULT "); break; default: for (c = acslist; c->name; c++) if (ap->can & c->flag) fprintf(fp, "%s ", c->name); break; } switch (ap->cant) { case ACS_DEFAULT: fprintf(fp, "NONE "); break; default: for (c = acslist; c->name; c++) if (c->toggle && (ap->cant & c->flag)) fprintf(fp, "!%s ", c->name); break; } if (ap->comment) fprintf(fp, "# %s\n", ap->comment); else fputc('\n', fp); } fclose(fp); rename_file(tmpf, ACCESS_FILE); } reserve_fd(); return; }
string create_backup( string filename ){ char numTag[6]; string resultant_name; for( int i = 0; i < 100000; i++ ){ sprintf( numTag, "%5d", i ); resultant_name = ( filename + string( numTag ) ); if( not system( ( string( "test -e " ) + enclosed( resultant_name ) ) ) ) if( rename_file( filename, resultant_name ) ) return resultant_name; } return string( "" ); }
/*\ |*| Rename a file, but first move away the destination \*/ int rename_away(u16 *src, u16 *dst) { if (move_away(dst, ".bad")) { fprintf(stderr, " Rename: %s", basename(src)); fprintf(stderr, " -> %s : ", basename(dst)); fprintf(stderr, "File exists\n"); return -1; } else if (rename_file(src, dst)) { return -1; } else { return 0; } }
static void renamedir(struct benchfiles *dirs, randdata_t *rd) { struct ffsb_file *dir; char *oldname; dir = choose_file_writer(dirs, rd); oldname = dir->name; rename_file(dir); if (rename(oldname, dir->name) < 0) { perror("rename"); exit(1); } unlock_file_writer(dir); free(oldname); }
/* menu callbacks */ void cb_ctx_manual_rename(GtkWidget *widget, GdkEvent *event) { GtkTreeModel *model; GtkTreeIter iter; char *old_path; char *new_name; gtk_tree_view_get_first_selected(tv_files, &model, &iter); gtk_tree_model_get(model, &iter, 1, &old_path, -1); new_name = rename_prompt_new_name(g_path_get_basename(old_path)); if (new_name == NULL) return; rename_file(old_path, new_name, TRUE); //gtk_list_store_set(GTK_LIST_STORE(model), &iter, 4, new_name, -1); free(new_name); }
static void cb_file_edited (GtkCellRendererText *renderer, gchar *strPath, gchar *new_path, gpointer user_data) { GtkTreeIter iter; GtkTreeModel *model = gtk_tree_view_get_model(tv_files); GtkTreePath *path = gtk_tree_path_new_from_string(strPath); if(path != NULL && gtk_tree_model_get_iter(model, &iter, path)) { gchar* old_path; gtk_tree_model_get(model, &iter, 4, &old_path, -1); if(g_strcmp0(old_path, new_path)) { rename_file(old_path, new_path, FALSE); //gtk_list_store_set(GTK_LIST_STORE(model), &iter, 4, new_path, -1); } gtk_tree_path_free(path); } }
static int install_modify_line(int modified_line_num, const char *modified_line) { FILE *in; FILE *out; char line[1002]; char *Pc; int r, line_count; in = jp_open_home_file(EPN".install", "r"); if (!in) { jp_logf(JP_LOG_DEBUG, "failed opening install_file\n"); return EXIT_FAILURE; } out = jp_open_home_file(EPN".install.tmp", "w"); if (!out) { fclose(in); jp_logf(JP_LOG_DEBUG, "failed opening install_file.tmp\n"); return EXIT_FAILURE; } /* Delete line by copying file and skipping over line to delete */ for (line_count=0; !feof(in); line_count++) { line[0]='\0'; Pc = fgets(line, 1000, in); if (!Pc) { break; } if (line_count == modified_line_num) { r = fprintf(out, "%s\n", modified_line); } else { r = fprintf(out, "%s", line); } if (r==EOF) { break; } } fclose(in); fclose(out); rename_file(EPN".install.tmp", EPN".install"); return EXIT_SUCCESS; }
static void cmd_ctrl_m(key_info_t key_info, keys_info_t *keys_info) { leave_change_mode(0); if(curr == 2) rename_file(view, 0); #ifndef _WIN32 else if(curr == 4) change_owner(); else if(curr == 6) change_group(); else if(curr == 8) enter_attr_mode(view); #else else if(curr == 4) enter_attr_mode(view); #endif }
void write_info_file(void) { char info_file[PATH_MAX]; char tmp_file[PATH_MAX]; (void)snprintf(info_file, sizeof(info_file), "%s/vifminfo", cfg.config_dir); (void)snprintf(tmp_file, sizeof(tmp_file), "%s_%u", info_file, get_pid()); if(os_access(info_file, R_OK) != 0 || copy_file(info_file, tmp_file) == 0) { update_info_file(tmp_file); if(rename_file(tmp_file, info_file) != 0) { LOG_ERROR_MSG("Can't replace vifminfo file with its temporary copy"); (void)remove(tmp_file); } } }
void DebugFile::init( std::string filename ) { this->filename = filename; const std::string oldfile = filename + ".prev"; bool rename_failed = false; struct stat buffer; if( stat( filename.c_str(), &buffer ) == 0 ) { // Continue with the old log file if it's smaller than 1 MiB if( buffer.st_size >= 1024 * 1024 ) { rename_failed = !rename_file( filename, oldfile ); } } file.open( filename.c_str(), std::ios::out | std::ios::app ); file << "\n\n-----------------------------------------\n"; currentTime() << " : Starting log."; if( rename_failed ) { DebugLog( D_ERROR, DC_ALL ) << "Moving the previous log file to " << oldfile << " failed.\n" << "Check the file permissions. This program will continue to use the previous log file."; } }
void logger_file_write(void *generic_info,int length) { FILE *logger_write_fp; int status = 0; char version = 0x01; int log_file_size = 0; logger_write_fp = fopen(LOG_FILE, "a"); if (logger_write_fp == NULL) { ALOGE("fopen failure for power_supply_info.bin,errno = %d (%s)",errno,strerror(errno)); } else { /* update the log_file_size on every log write */ fseek(logger_write_fp, 0L, SEEK_END); log_file_size = ftell(logger_write_fp); fseek(logger_write_fp, 0L, SEEK_SET); if (log_file_size <= 0 ) { /* update file version number ,0x01,0x02,0x03 etc */ fwrite(&version,sizeof(version),1,logger_write_fp); log_file_size += 1; } fwrite(generic_info,length,1,logger_write_fp); log_file_size += length; /* check whether file size has exceeded 3MB,if so rename file */ if (log_file_size > MAX_LOG_FILE_SIZE) { fclose(logger_write_fp); ALOGD("file rename called"); status = rename_file(LOG_FILE,OLD_LOG_FILE); if (status < 0) ALOGE("renaming failed,errno = %d (%s)",errno,strerror(errno)); log_file_size = 0; return; } fclose(logger_write_fp); } }
/* * Rewrite the newsrc file, without the specified group */ void delete_group( char *group) { FILE *fp; FILE *newfp; char *line; char *seq; int sub; if (no_write) return; if ((newfp = fopen(newnewsrc, "w" FOPEN_OPTS)) != NULL) { #ifndef M_OS2 if (newsrc_mode) fchmod(fileno(newfp), newsrc_mode); #endif /* !M_OS2 */ if ((fp = fopen(newsrc, "r")) != NULL) { while ((line = tin_fgets(fp, FALSE)) != NULL) { seq = parse_newsrc_line(line, &sub); if (!STRCMPEQ(line, group)) fprintf(newfp, "%s%c %s\n", line, sub, seq); } fclose(fp); } if (ferror(newfp) || fclose(newfp)) { error_message(_(txt_filesystem_full), NEWSRC_FILE); unlink(newnewsrc); } else rename_file(newnewsrc, newsrc); } }
int main(int argn ,char *argv[]) { char in[100]; while(1) { int n = strlen(para[0]); printf("%s->", para[0]); memset(in, 0, sizeof(in)); gets(in); int choice = explain(in); //根据命令解释器的返回结果执行相对应的命令 switch(choice) { case -1: printf("' %s '不是内部或外部命令,也不是可运行的程序\n或批处理文件。\n", in);break; case 0 : show_time();break; case 1 : show_version();break; case 2 : show_date();break; case 3 : clrscr(0, 0);break; case 4 : show_directory();break; case 5 : help();break; case 6 : show_current_tree(para[0], 0);break; case 7 : return 0; case 8 : print_text(para[0]);break; case 9 : if(del_dir(para[0]) == 0) del_files(para[0]);break;//如果para[0]是文件夹,则执行删除文件夹函数,否则执行文件删除函数 case 10 : creat_dir(para[0]);break; case 11 : rename_file(para[0], para[1]);break; case 12 : change_path(in);break; }//{"time", "version", "date", "cls", "dir", "help", "tree", "print", "del", "mkdir", "ren"}; if(choice != 12)//如果没有改变路径,则每次都把当前工作目录下的以外的其它字符清除 { memset(para[0] + n, 0, (100 - n) * sizeof(char)); memset(para[1] + n, 0, (100 - n) * sizeof(char)); } } return 0; }
/* * function rotate log depends on file's size ,if the * file size more than maxsize ,the file will cut apart * and usr can configure the maxsize */ int rotate_logs(char *logpath) { if (get_file_size(logpath) >= g_logfilesize_max) { char buf[1028] = { 0 }; strcpy(buf, logpath); int len = strlen(buf); int num = get_file_num(logpath); if (num == g_logfilenum_max) { strcat(buf, "-"); buf[len + 1] = g_logfilenum_max + '0' - 1; buf[len + 2] = '\0'; unlink(buf); } rename_file(logpath, num); } return 0; }
static int msfs_rename(const char * from, const char * to) { reset_error(); rename_file(from, to); return msfs_error; }
/** * main */ int main(int argc, const char **argv) { // Our main data storage vessel.. RASPISTILLYUV_STATE state; int exit_code = EX_OK; MMAL_STATUS_T status = MMAL_SUCCESS; MMAL_PORT_T *camera_preview_port = NULL; MMAL_PORT_T *camera_video_port = NULL; MMAL_PORT_T *camera_still_port = NULL; MMAL_PORT_T *preview_input_port = NULL; FILE *output_file = NULL; bcm_host_init(); // Register our application with the logging system vcos_log_register("RaspiStill", VCOS_LOG_CATEGORY); signal(SIGINT, signal_handler); // Disable USR1 for the moment - may be reenabled if go in to signal capture mode signal(SIGUSR1, SIG_IGN); default_status(&state); // Do we have any parameters if (argc == 1) { fprintf(stdout, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING); display_valid_parameters(basename(argv[0])); exit(EX_USAGE); } default_status(&state); // Parse the command line and put options in to our status structure if (parse_cmdline(argc, argv, &state)) { status = -1; exit(EX_USAGE); } if (state.verbose) { fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING); dump_status(&state); } // OK, we have a nice set of parameters. Now set up our components // We have two components. Camera and Preview // Camera is different in stills/video, but preview // is the same so handed off to a separate module if ((status = create_camera_component(&state)) != MMAL_SUCCESS) { vcos_log_error("%s: Failed to create camera component", __func__); exit_code = EX_SOFTWARE; } else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS) { vcos_log_error("%s: Failed to create preview component", __func__); destroy_camera_component(&state); exit_code = EX_SOFTWARE; } else { PORT_USERDATA callback_data; if (state.verbose) fprintf(stderr, "Starting component connection stage\n"); camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT]; camera_video_port = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT]; camera_still_port = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT]; // Note we are lucky that the preview and null sink components use the same input port // so we can simple do this without conditionals preview_input_port = state.preview_parameters.preview_component->input[0]; // Connect camera to preview (which might be a null_sink if no preview required) status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection); if (status == MMAL_SUCCESS) { VCOS_STATUS_T vcos_status; // Set up our userdata - this is passed though to the callback where we need the information. // Null until we open our filename callback_data.file_handle = NULL; callback_data.pstate = &state; vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0); vcos_assert(vcos_status == VCOS_SUCCESS); camera_still_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data; if (state.verbose) fprintf(stderr, "Enabling camera still output port\n"); // Enable the camera still output port and tell it its callback function status = mmal_port_enable(camera_still_port, camera_buffer_callback); if (status != MMAL_SUCCESS) { vcos_log_error("Failed to setup camera output"); goto error; } if (state.verbose) fprintf(stderr, "Starting video preview\n"); int frame, keep_looping = 1; FILE *output_file = NULL; char *use_filename = NULL; // Temporary filename while image being written char *final_filename = NULL; // Name that file gets once writing complete frame = 0; while (keep_looping) { keep_looping = wait_for_next_frame(&state, &frame); // Open the file if (state.filename) { if (state.filename[0] == '-') { output_file = stdout; // Ensure we don't upset the output stream with diagnostics/info state.verbose = 0; } else { vcos_assert(use_filename == NULL && final_filename == NULL); status = create_filenames(&final_filename, &use_filename, state.filename, frame); if (status != MMAL_SUCCESS) { vcos_log_error("Unable to create filenames"); goto error; } if (state.verbose) fprintf(stderr, "Opening output file %s\n", final_filename); // Technically it is opening the temp~ filename which will be ranamed to the final filename output_file = fopen(use_filename, "wb"); if (!output_file) { // Notify user, carry on but discarding encoded output buffers vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, use_filename); } } callback_data.file_handle = output_file; } if (output_file) { int num, q; // There is a possibility that shutter needs to be set each loop. if (mmal_status_to_int(mmal_port_parameter_set_uint32(state.camera_component->control, MMAL_PARAMETER_SHUTTER_SPEED, state.camera_parameters.shutter_speed) != MMAL_SUCCESS)) vcos_log_error("Unable to set shutter speed"); // Send all the buffers to the camera output port num = mmal_queue_length(state.camera_pool->queue); for (q=0;q<num;q++) { MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.camera_pool->queue); if (!buffer) vcos_log_error("Unable to get a required buffer %d from pool queue", q); if (mmal_port_send_buffer(camera_still_port, buffer)!= MMAL_SUCCESS) vcos_log_error("Unable to send a buffer to camera output port (%d)", q); } if (state.burstCaptureMode && frame==1) { mmal_port_parameter_set_boolean(state.camera_component->control, MMAL_PARAMETER_CAMERA_BURST_CAPTURE, 1); } if (state.verbose) fprintf(stderr, "Starting capture %d\n", frame); if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS) { vcos_log_error("%s: Failed to start capture", __func__); } else { // Wait for capture to complete // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic vcos_semaphore_wait(&callback_data.complete_semaphore); if (state.verbose) fprintf(stderr, "Finished capture %d\n", frame); } // Ensure we don't die if get callback with no open file callback_data.file_handle = NULL; if (output_file != stdout) { rename_file(&state, output_file, final_filename, use_filename, frame); } } if (use_filename) { free(use_filename); use_filename = NULL; } if (final_filename) { free(final_filename); final_filename = NULL; } } // end for (frame) vcos_semaphore_delete(&callback_data.complete_semaphore); } else { mmal_status_to_int(status); vcos_log_error("%s: Failed to connect camera to preview", __func__); } error: mmal_status_to_int(status); if (state.verbose) fprintf(stderr, "Closing down\n"); if (output_file) fclose(output_file); // Disable all our ports that are not handled by connections check_disable_port(camera_video_port); if (state.preview_connection) mmal_connection_destroy(state.preview_connection); /* Disable components */ if (state.preview_parameters.preview_component) mmal_component_disable(state.preview_parameters.preview_component); if (state.camera_component) mmal_component_disable(state.camera_component); raspipreview_destroy(&state.preview_parameters); destroy_camera_component(&state); if (state.verbose) fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n"); } if (status != MMAL_SUCCESS) raspicamcontrol_check_configuration(128); return exit_code; }
static gint collection_save_private(CollectionData *cd, const gchar *path) { FILE *f; GList *work; gchar *tmp_path; gchar *pathl; mode_t save_mask; if (!path && !cd->path) return FALSE; if (!path) { path = cd->path; } tmp_path = unique_filename(path, ".tmp", "_", 3); if (!tmp_path) return FALSE; pathl = path_from_utf8(tmp_path); save_mask = umask(0077); f = fopen(pathl, "w"); umask(save_mask); g_free(pathl); if (!f) { /* file open failed */ printf("failed to open collection (write) \"%s\"\n", tmp_path); g_free(tmp_path); return FALSE; } fprintf(f, "%s collection\n", GQVIEW_COLLECTION_MARKER); fprintf(f, "#created with GQview version %s\n", VERSION); collection_update_geometry(cd); if (cd->window_read) { fprintf(f, "#geometry: %d %d %d %d\n", cd->window_x, cd->window_y, cd->window_w, cd->window_h); } work = cd->list; while (work) { CollectInfo *ci = work->data; if (fprintf(f, "\"%s\"\n", ci->path) < 0) { fclose(f); printf("Error writing to %s\n", tmp_path); unlink_file(tmp_path); g_free(tmp_path); return FALSE; } work = work->next; } fprintf(f, "#end\n"); fclose(f); copy_file_attributes(path, tmp_path, TRUE, FALSE); if (!rename_file(tmp_path, path)) { printf("collection save unable to rename %s to %s\n", tmp_path, path); unlink_file(tmp_path); g_free(tmp_path); return FALSE; } g_free(tmp_path); if (!cd->path || strcmp(path, cd->path) != 0) { gchar *buf = cd->path; cd->path = g_strdup(path); path = cd->path; g_free(buf); g_free(cd->name); cd->name = g_strdup(filename_from_path(cd->path)); collection_path_changed(cd); } cd->changed = FALSE; return TRUE; }