Ejemplo n.º 1
0
int fs_insert(FileSystem *fs, const char *f, int pos, int l, const char *data) {
    Inode *inode = NULL;
    char *buffer = NULL;
    File *file = NULL;
    int i = 0;
    
    inode = folder_lookup(fs, fs->cur, f);
    if (!inode) return ERROR;
    buffer = (char *) malloc(inode->filesize + l);
    if (!buffer) return ERROR;
    file = file_new(fs, inode);
    file_get_contents(file, buffer);
    file_free(&file);
    if (pos > inode->filesize) {
        pos = inode->filesize;
    }
    for (i = inode->filesize - 1; i >= pos; --i) {
        buffer[i + l] = buffer[i];
    }
    memcpy(buffer + pos, data, l);
    file = file_new(fs, inode);
    file_put_contents(file, buffer, inode->filesize + l);
    file_free(&file);
    free(buffer);
    return OK;
}
Ejemplo n.º 2
0
Folder* folder_open(FileSystem *fs, Inode *inode) {
    Folder *folder = NULL;
    char *buffer = NULL;
    int offset = 0;
    int i = 0;
    
    folder = (Folder *) malloc(sizeof(Folder));
    file_init(AS_FILE(folder), fs, inode);
    buffer = (char *) malloc(inode->filesize);
    file_get_contents(AS_FILE(folder), buffer);
#ifdef DEBUG
    fprintf(stderr, "folder_open buffer=");
    for (i = 0; i < inode->filesize; ++i) fprintf(stderr, " %x", buffer[i]);
    fprintf(stderr, "\n");
#endif
    folder->nitem = util_readint(buffer, 0);
#ifdef DEBUG
    fprintf(stderr, "folder_open, folder->nitem=%d\n", folder->nitem);
#endif
    folder->items = (FolderItem *) malloc(sizeof(FolderItem) * folder->nitem);
    offset = 4;
    for (i = 0; i < folder->nitem; ++i) {
        int cname_len = 0;
        
        cname_len = util_readint(buffer, offset);
        offset += 4;
        memcpy(folder->items[i].cname, buffer + offset, cname_len);
        folder->items[i].cname[cname_len] = 0;  // make it a string
        offset += cname_len;
        folder->items[i].page_num = util_readint(buffer, offset);
        offset += 4;
    }
    free(buffer);
    return folder;
}
Ejemplo n.º 3
0
int fs_delete(FileSystem *fs, const char *f, int pos, int l) {
    Inode *inode = NULL;
    char *data = NULL;
    File *file = NULL;
    int i = 0;
    
    inode = folder_lookup(fs, fs->cur, f);
    if (!inode) return ERROR;
    data = (char *) malloc(inode->filesize);
    if (!data) return ERROR;
    file = file_new(fs, inode);
    file_get_contents(file, data);
    file_free(&file);
    if (pos + l > inode->filesize) {
        l = inode->filesize - pos;
    }
    for (i = pos + l; i < inode->filesize; ++i) {
        data[i - l] = data[i];
    }
    file = file_new(fs, inode);
    file_put_contents(file, data, inode->filesize - l);
    file_free(&file);
    free(data);
    return OK;
}
Ejemplo n.º 4
0
int como_ast_create(const char *filename)
{
    ast_node* statements;
    yyscan_t scanner;
    YY_BUFFER_STATE state;
    char* text;

    text = file_get_contents(filename);

    if(!text) {
        printf("file '%s' not found\n", filename);
        return 1;
    }
    
    if(yylex_init(&scanner)) {
        como_error_noreturn("yylex_init returned NULL");
    }

    state = yy_scan_string(text, scanner);

    if(yyparse(&statements, scanner)) {
        como_error_noreturn("yyparse returned NULL");
    }

    yy_delete_buffer(state, scanner);

    yylex_destroy(scanner);

    como_compile_ast(statements, filename);

    return 0;
}
Ejemplo n.º 5
0
static void run_ascii_test(){

    char *filename = "myfile775384905723345.txt";

    //create a temp file and close it
        char *file_contents = "Hi, I'm file contents.";
        FILE *file = fopen( filename, "w+" );
        fwrite( file_contents, sizeof(char), strlen(file_contents), file );
        fclose( file );

    //open the temp file for reading and use "file_get_contents"
        FILE *file2 = fopen( filename, "r+" );
        wide_char **string_ptr = malloc( sizeof(wide_char*) );
        file_get_contents( string_ptr, file2 );
        fclose( file2 );

    //ensure that it's the same as what I had put in
        //assert( strcmp(file_contents,*string_ptr) == 0 );

    //cleanup
        unlink( filename );
        free( *string_ptr );
        free( string_ptr );

}
Ejemplo n.º 6
0
int file_get_contents_nothrow(StreamBuffer &contents, const char *path){
	try {
		file_get_contents(contents, path);
		return 0;
	} catch(SystemException &e){
		return e.code();
	}
}
Ejemplo n.º 7
0
BOOL file_get_contents(LPCTSTR lpszFilename, CString &strBuffer)
{
	CStringA strA;
	BOOL bRet = file_get_contents(lpszFilename, strA);

	USES_CONVERSION;
	strBuffer = CA2CT( strA );		
	return bRet;
}
static int loadSpec(const char * filename) {
    int error = 0;
    char * data = NULL;
    size_t data_len = 0;
    struct json_object * result = NULL;
    struct json_object * array_item = NULL;
    int array_len = 0;
    
    // Read JSON file
    error = file_get_contents(filename, &data, &data_len);
    if( error != 0 ) {
        fprintf(stderr, "Failed to read spec file: %s, code: %d\n", filename, error);
        goto error;
    }
    
    // Parse JSON
    result = json_tokener_parse(data);
    // @todo: parsing errors seem to cause segfaults....
    if( result == NULL ) {
        fprintf(stderr, "Failed so parse JSON\n");
        error = 1;
        goto error;
    }
    
    // Root object should be array
    if( json_object_get_type(result) != json_type_array ) {
        fprintf(stderr, "Root JSON value was not array\n");
        error = 1;
        goto error;
    }
    
    // Get number of test cases
    array_len = json_object_array_length(result);
    
    // Allocate tests array
    tests_size = array_len + 1;
    tests = talloc_zero_array(rootctx, struct tokenizer_test, tests_size);
    
    // Iterate over array
    for( int i = 0; i < array_len; i++ ) {
        array_item = json_object_array_get_idx(result, i);
        if( json_object_get_type(array_item) != json_type_object ) {
            fprintf(stderr, "Warning: test case was not an object\n");
            continue;
        }
        loadSpecTest(array_item);
    }
error:
    if( data ) {
        free(data);
    }
    if( result ) {
        json_object_put(result);
    }
    return error;
}
Ejemplo n.º 9
0
// ***************************************************
int get_urls( a_array *urls, char *file )
{
  // Check if file exists
  if(! file_exists( file ) )
    return -1;

  // Open file and read its content
  char *data = file_get_contents( file, FT_TEXT );

  // How big our file was?
  int size = strlen( data );
  int i;

  // This is a dirty way... make a better one some day.
  for( i=0; i<size; i++ )
  {
    // If there is "http" text, then we have to search until we
    // found " char from our string.
    if( i>0 && data[i-1] == '"' && data[i] == 'h' && data[i+1] == 't'
        && data[i+2] == 't' && data[i+3] == 'p' )
    {
      char ch;

      // Start point from data-array.
      int counter = i;

      // Free memory to our string
      char *string = malloc( 1024 );
      int tmp_counter = 0;

      // Copy string until " is reached.
      while( ( ch = data[counter] ) != '"' )
      {
        // Copy char to string and add tmp_counter and counter values.
        string[tmp_counter] = ch;
        tmp_counter++;
        counter++;
      }

      // Add \0 in the end
      string[tmp_counter] = '\0';

      // Add our string to array
      array_add( urls, string );

      // Free memory of our string
      free( string );
    }
  }

  // Free data where is our file.
  free( data );

  return 0;
}
Ejemplo n.º 10
0
int read_pid(){
	if(app_args.pidfile.empty()){
		return -1;
	}
	std::string s;
	file_get_contents(app_args.pidfile, &s);
	if(s.empty()){
		return -1;
	}
	return str_to_int(s);
}
Ejemplo n.º 11
0
/* 对模板文件进行编译.*/
int _lua_tpl_compile(lua_State * L)
{
    int cache = 0,lbuf = 0;
    unsigned int _var_size = 0;
    size_t lfile;

    const char *cfile = NULL,
                * file= luaL_checklstring(L, 1,&lfile),
                  * buf = NULL;
#if defined(_WIN32) || defined(_WIN64)
    automem_t mem= {NULL};
#else
    automem_t mem= {
        .size = 0,
        .pdata = NULL
    };
#endif

    if(lua_isboolean(L, 2))
        cache =lua_toboolean(L, 2);

    if(0 != cache) {
        struct stat st1,st2;
        cfile=(char *)malloc(lfile+5);
        memcpy((char *)cfile,file,lfile);
        strcpy((char *)cfile+lfile,".tpl");
        if((0 == stat(file,&st1)) && (0 == stat(cfile, &st2)))
        {
            if(st1.st_mtime <= st2.st_mtime) {
                read_from_cached(L, &mem, cfile);
                free((void*)cfile);
                lua_pushlstring(L, mem.pdata, mem.size);
                goto lua_tpl_compile_final;
            }
        }
    }

    if(NULL != (buf = file_get_contents(file, &lbuf)))
    {
        lua_tpl_expand_variables(L, &mem, lbuf);
        _var_size = mem.size;
        lua_tpl_compile_local(L, &mem, buf, lbuf);
        free((void*)buf);
        lua_pushlstring(L,(char *)mem.pdata,mem.size);
    }
    if(0 != cache && mem.pdata != NULL)
        file_put_contents(cfile, mem.pdata + _var_size, mem.size - _var_size);

    if(NULL != cfile)
        free((void *)cfile);
lua_tpl_compile_final:
    automem_uninit(&mem);
    return 1;
}
Ejemplo n.º 12
0
int
wiki_load_data(const char *page, char **result)
{
	char		filename[PATH_MAX];

	snprintf(filename, sizeof filename, "%s/%s/latest",
	    config.contents_dir, page);

	DPRINTF("reading file %s\n", filename);
	return file_get_contents(filename, result);
}
Ejemplo n.º 13
0
int main() {
  int i;
  for(i = 0; i < 100; i++) {
    init();
    file_get_contents(input_buffer, "spec/fixtures/tables_help");
    parse();
    printf("%d\n", i);
    cleanup();
  }
  return 0;
}
Ejemplo n.º 14
0
void getcfg() {
	char* __homedir="/sdcard/";
	int i;

	if (__homedir==NULL) {
 		strcpy(__configPath, configfile_fallback); // если у юзера отсутствует домашний каталог, то держим все данные прямо здесь, рядом
  	} else {
   		strcpy(__configPath, __homedir);
		strcat(__configPath, "/"); // на всякий случай добавляем слэш

		if (!dir_exists(__configPath)) {
			printf("Пытаемся создать каталог для конфига\n");
			mkdir_p(__configPath, 0666);
		}

		strcat(__configPath, configfile);
	}
	
	FILE *f;

	if (access(__configPath, R_OK) == -1) {
		printf("Конфиг не существует, пытаемся скопировать дефолтный...\n");
		
		f=fopen(__configPath, "w");
		if (!f) {
			printf("Не получается записать дефолтный конфиг! =(\n");
		} else {
			fputs(configtext_default, f);
			fclose(f);
		}
	}

	char* config=file_get_contents(__configPath);
	
	if (config!=NULL) {
		struct list config_lines=split(config, "\n");

		if (config_lines.length<2) {
			printf ("Формат конфига неверный, пропускаем.\n");
		} else {
			sscanf(config_lines.index[0], "%d:%d:%d:%d", &start_lessons[0], &start_lessons[1], &localtime_offset, &notify_offset);
			sscanf(config_lines.index[1], "%d:%d:%d", &count_lessons, &lesson_length, &default_break);
		}

		for (i=2; i<config_lines.length; i++) {
			if ((i-2)>BREAKS_MAX_INDEX) break;
			sscanf(config_lines.index[i], "%d", &breaks_in_minutes[i-2]);
		}
	} else {
		printf("Невозможно прочесть конфиг, используются значения по-умолчанию.\n");
	}
}
Ejemplo n.º 15
0
char *
wiki_load_generated(const char *page)
{
	char		filename[PATH_MAX];
	char		*result;

	snprintf(filename, sizeof filename, "%s/%s/generated.html",
	    config.contents_dir, page);

	file_get_contents(filename, &result);

	return (result);
}
Ejemplo n.º 16
0
void fs_cat(FileSystem *fs, const char *f, FILE *fp) {
    Inode *inode = NULL;
    char *data = NULL;
    File *file = NULL;
    
    inode = folder_lookup(fs, fs->cur, f);
    data = (char *) malloc(inode->filesize);
    file = file_new(fs, inode);
    file_get_contents(file, data);
    file_free(&file);
    fprintf(fp, "%s\n", data);
    fflush(fp);
    free(data);
}
Ejemplo n.º 17
0
void Shader::load(const char* filename){

  std::string file = file_get_contents(filename);
  
  char const * source[1] { file.c_str() };
  
  if(!source[0]){
    std::cout << "Couldn't load shader " << file << '\n';
    return;
  }
  
  glShaderSource(*id, 1, source, NULL);
  
}
Ejemplo n.º 18
0
int
item_bin_sort_file(char *in_file, char *out_file, struct rect *r, int *size)
{
	int j,k,count,rc=0;
	struct coord *c;
	struct item_bin *ib;
	FILE *f;
	unsigned char *p,**idx,*buffer;
	if (file_get_contents(in_file, &buffer, size)) {
		ib=(struct item_bin *)buffer;
		p=buffer;
		count=0;
		while (p < buffer+*size) {
			count++;
			p+=(*((int *)p)+1)*4;
		}
		idx=g_malloc(count*sizeof(void *));
		p=buffer;
		for (j = 0 ; j < count ; j++) {
			idx[j]=p;
			p+=(*((int *)p)+1)*4;
		}
		qsort(idx, count, sizeof(void *), item_bin_sort_compare);
		f=fopen(out_file,"wb");
		for (j = 0 ; j < count ; j++) {
			ib=(struct item_bin *)(idx[j]);
			c=(struct coord *)(ib+1);
			fwrite(ib, (ib->len+1)*4, 1, f);
			if (r) {
				for (k = 0 ; k < ib->clen/2 ; k++) {
					if (rc) 
						bbox_extend(&c[k], r);
					else {
						r->l=c[k];
						r->h=c[k];
					}
					rc++;
				}
			}
		}
		fclose(f);
		g_free(idx);
		g_free(buffer);
		return 1;
	}
	return 0;
}
Ejemplo n.º 19
0
int
main(int argc, char *argv[])
{
  if (1 == argc || 0 == strcmp("--help", argv[1]) || 0 == strcmp("-h", argv[1])) {
    usage(argv);
    exit(EXIT_FAILURE);
  }

  bool failed = false;
  std::cout << std::endl;
  while (--argc > 0) {
    std::cout << "Minifaction of file: " << argv[argc] << std::endl;

    std::string json;
    try {
      json = file_get_contents(argv[argc]);
    } catch (const std::exception& e) {
      std::cout << "[!] Could not read file." << std::endl;
      std::cout << "Continuing..." << std::endl << std::endl;
      failed = true;
      continue;
    }

    std::string outfile(argv[argc]);
    outfile += ".min";
    std::ofstream file(outfile.c_str());
    if (!file) {
      std::cout << "[!] Could not open file for writing: " << outfile << std::endl;
      std::cout << "Continuing..." << std::endl << std::endl;
      continue;
    }

    file << Json::Value::minify(json);
    file.close();

    std::cout << "Complete." << std::endl << std::endl;
  }

  std::cout << "Minification process complete." << std::endl;
  if (failed) {
    std::cout << "[!] However, there were some files that failed." << std::endl;
    exit(EXIT_FAILURE);
  }

  exit(EXIT_SUCCESS);
}
Ejemplo n.º 20
0
    void Backend::loadConfig(std::string filename)
    {
        std::string data = file_get_contents(filename);
        Json::Reader reader;
        Json::Value json;

        if (reader.parse(data, json)) {
            if (json.isMember("backlash")) {
                config.backlash = json["backlash"].asBool();
            }
            if (json.isMember("mode")) {
                if (json["mode"].asString() == "motor") {
                    config.mode = MODE_MOTORS;
                } else {
                    config.mode = MODE_TORQUE;
                }
            }
            if (json.isMember("density")) {
                config.density = json["density"].asDouble();
            }
            if (json.isMember("gain")) {
                config.gain = json["gain"].asDouble();
            }
            if (json.isMember("voxelsResolution")) {
                config.voxelsResolution = json["voxelsResolution"].asDouble();
            }
            if (json.isMember("motors")) {
                for (auto &entry : json["motors"].getMemberNames()) {
                    auto &motor = json["motors"][entry];
                    if (motor.isMember("maxTorque")) {
                        config.motors[entry].maxTorque = motor["maxTorque"].asDouble();
                    }
                    if (motor.isMember("maxSpeed")) {
                        config.motors[entry].maxSpeed = motor["maxSpeed"].asDouble();
                    }
                    if (motor.isMember("speedGain")) {
                        config.motors[entry].speedGain = motor["speedGain"].asDouble();
                    }
                    if (motor.isMember("torqueGain")) {
                        config.motors[entry].torqueGain = motor["torqueGain"].asDouble();
                    }
                }
            }
        }
    }
Ejemplo n.º 21
0
int BEE::Room::load_instance_map(std::string fname) {
	if (game->get_is_ready()) {
		instance_map = fname;
		game->restart_room();
		return 0;
	}

	std::vector<std::tuple<Object*,int,int>> data;
	std::string datastr = file_get_contents(fname);
        if (!datastr.empty()) {
                std::istringstream data_stream (datastr);

                while (!data_stream.eof()) {
                        std::string tmp;
                        getline(data_stream, tmp);

                        if (tmp.empty()) {
                                continue;
                        }

			std::string v;
                        std::stringstream vs (tmp);
                        getline(vs, v, ',');
                        v = trim(v);

                        std::string d = tmp.substr(tmp.find(",")+1);
                        d = trim(d);
			int x = std::stoi(d.substr(0, d.find(",")));
			int y = std::stoi(d.substr(d.find(",")+1));

                        data.push_back(std::make_tuple(game->get_object_by_name(v), x, y));
                }

		for (auto& i : data) {
			add_instance(-1, std::get<0>(i), std::get<1>(i), std::get<2>(i));
		}
        } else {
		std::cerr << "No instances loaded.\n";
		return 1;
	}

	return 0;
}
Ejemplo n.º 22
0
static xcb_xrm_database_t *__xcb_xrm_database_from_file(const char *_filename, const char *base, int depth) {
    char *filename = NULL;
    char *copy = NULL;
    char *new_base = NULL;
    char *content = NULL;
    xcb_xrm_database_t *database = NULL;

    if (_filename == NULL)
        return NULL;

    filename = resolve_path(_filename, base);
    if (filename == NULL)
        return NULL;

    /* We need to strdup() the filename since dirname() will modify it. */
    copy = strdup(filename);
    if (copy == NULL)
        goto done_from_file;

    new_base = dirname(copy);
    if (new_base == NULL)
        goto done_from_file;

    content = file_get_contents(filename);
    if (content == NULL)
        goto done_from_file;

    database = __xcb_xrm_database_from_string(content, new_base, depth);

done_from_file:
    FREE(filename);
    FREE(copy);
    FREE(content);

    return database;
}
Ejemplo n.º 23
0
static void run_unicode_test(){

    char *source_filename = "test/test_files/utf8_two_lines.txt";
    char *destination_filename = "test/test_files/utf8_two_lines_destination.txt";

    //open the source file for reading and use "file_get_contents"
        FILE *file1 = fopen( source_filename, "r+" );
        wide_char *string_ptr;
        size_t number_of_characters = file_get_contents( &string_ptr, file1 );
        fclose( file1 );

    //open the destination file for writing and write the contents
        FILE *file2 = fopen( destination_filename, "w+" );
        if( file2 == NULL ){
            printf( "Could not open destination file for writing: %s", destination_filename );
            exit(5);
        }
        fwrite( string_ptr, sizeof(wide_char), number_of_characters, file2 );
        fclose( file2 );
        //printf( "number of characters: %lu", number_of_characters );

        const unsigned char comparison_string[596] = {
            0xFF, 0xFE, 0x00, 0x00, 0x91, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0x92, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x93, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x94, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0x95, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0x96, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x97, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x98, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0x99, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0x9A, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x9B, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x9C, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0x9D, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0x9E, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x9F, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xA0, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xA1, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xA3, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xA4, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xA5, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xA6, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xA7, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xA8, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xA9, 0x03, 0x00, 0x00, 0x2E, 0x00, 0x00, 0x00,
            0x0D, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0xB1, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xB2, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xB3, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xB4, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xB5, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xB6, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xB7, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xB8, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xB9, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xBA, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xBB, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xBC, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xBD, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xBE, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xBF, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xC1, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xC3, 0x03, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00,
            0xC2, 0x03, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xC4, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xC5, 0x03, 0x00, 0x00,
            0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xC6, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0xC7, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
            0xC8, 0x03, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xC9, 0x03, 0x00, 0x00,
            0x2E, 0x00, 0x00, 0x00
        };

        assert( number_of_characters == 149 );

    //ensure that it's the same as what I had put in
        assert( wcsncmp(string_ptr, (wide_char*)comparison_string, number_of_characters) == 0 );

    //cleanup
        free( string_ptr );

}
Ejemplo n.º 24
0
Archivo: file.c Proyecto: dzts/cprogram
int main(){
	char * filename = "1.txt";
	char * str = file_get_contents(filename);
	printf("%s",str);
	return 0;
}
Ejemplo n.º 25
0
int cardpeek_update_perform(void)
{
    const char* cardpeek_update_file = path_config_get_string(PATH_CONFIG_FILE_CARDPEEK_UPDATE);
    a_string_t *contents;
    update_t *update;
    int remove;
    update_item_t *item;
    time_t now = time(NULL);
    int updated = 0;
    char *url = NULL;
    char *local_file;
    char *local_dnld;
    unsigned char digest[SHA256_DIGEST_LENGTH];
    a_string_t *url_request;
    unsigned first_update;

    first_update = (unsigned)luax_variable_get_integer("cardpeek.updates.first_update");
    
    /* STEP 1: get cardpeek.update file */

    url=luax_variable_get_strdup("cardpeek.updates.url");

    if (url==NULL)
        url = g_strdup(DEFAULT_UPDATE_URL);

    log_printf(LOG_INFO,"Fetching '%s'",url);

    url_request = a_strnew(NULL);
    a_sprintf(url_request,"%s?u=%x&v=%s",url,first_update,VERSION);

    if (http_download(a_strval(url_request),cardpeek_update_file)==0)
    {
        g_free(url);
        return 0;
    }
    g_free(url);
    a_strfree(url_request);


    /* STEP 2: parse file */

    if ((contents=file_get_contents(cardpeek_update_file))==NULL)
    {
        log_printf(LOG_ERROR,"failed to read update file information.");
        unlink(cardpeek_update_file);
        return 0;
    }

    update = update_new();

    if ((update_load(update,a_strval(contents),a_strlen(contents)))==0)
    {
        unlink(cardpeek_update_file);
        a_strfree(contents);
        update_free(update);
        return 0;
    }
    a_strfree(contents);

    /* log_printf(LOG_DEBUG,"Updates correctly loaded from '%s'",cardpeek_update_file); */
    if ((remove = update_filter_version(update,VERSION))>0)
        log_printf(LOG_WARNING,"%d updates will not be installed because they require a newer version of Cardpeek.");
    
    remove = update_filter_files(update);

    if (update->item_count)
        log_printf(LOG_INFO,"A total of %d files will be updated, %d files are kept unchanged.",update->item_count,remove);
    else
        log_printf(LOG_INFO,"No files will be updated, %d files are kept unchanged.",remove);

    item = update->items;

    while (item)
    {
        local_dnld = new_path(PATH_CONFIG_FOLDER_CARDPEEK,item->file,".download");
        local_file = new_path(PATH_CONFIG_FOLDER_CARDPEEK,item->file,NULL);

        if (http_download(item->url,local_dnld)!=0)
        {        
            if (sha256sum(local_dnld,digest))
            {
                if (memcmp(digest,bytestring_get_data(&item->digest),SHA256_DIGEST_LENGTH)==0)
                {
                    unlink(local_file);

                    if (rename(local_dnld,local_file)==0)
                    {
                        log_printf(LOG_INFO,"Successfuly updated %s", local_file);
                        updated++;
                    }
                    else
                    {
                        log_printf(LOG_ERROR,"Failed to copy %s to %s: %s", 
                                local_dnld,
                                local_file, 
                                strerror(errno));
                    }
                }
                else
                {
                    log_printf(LOG_WARNING,"File %s was not updated: authentication failed.",local_file);
                }
            }
            unlink(local_dnld);
        }
        g_free(local_dnld);
        g_free(local_file);
        item =  item->next; 
    }

    if (updated == update->item_count)
    {    
        luax_variable_set_integer("cardpeek.updates.next_update",(int)(now+7*(24*3600)));  
        luax_config_table_save();
    }

    unlink(cardpeek_update_file);
    update_free(update);

    /* STEP 3: finish */

    return 1;

}
Ejemplo n.º 26
0
Archivo: ocl.c Proyecto: Thundzz/GPU
void ocl_init(sotl_device_t *dev)
{
  cl_int err = 0;

  // Create context
  //
#ifdef HAVE_LIBGL
  if(dev->display) {
#ifdef __APPLE__
    CGLContextObj cgl_context = CGLGetCurrentContext ();
    CGLShareGroupObj sharegroup = CGLGetShareGroup (cgl_context);
    cl_context_properties properties[] = {
      CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
      (cl_context_properties) sharegroup,
      0
    };

#else
    cl_context_properties properties[] = {
      CL_GL_CONTEXT_KHR,
      (cl_context_properties) glXGetCurrentContext (),
      CL_GLX_DISPLAY_KHR,
      (cl_context_properties) glXGetCurrentDisplay (),
      CL_CONTEXT_PLATFORM, (cl_context_properties) dev->platform->id,
      0
    };
#endif

    dev->context = clCreateContext (properties, 1, &dev->id, NULL, NULL, &err);
  } else
#endif
    {
      dev->context = clCreateContext (0, 1, &dev->id, NULL, NULL, &err);
    }
    check (err, "Failed to create compute context \n");

    // Load program source
    //
    const char *opencl_prog;
    opencl_prog = file_get_contents(PROGRAM_NAME);
    if (!opencl_prog) {
        sotl_log(CRITICAL, "Failed to read contents of the OpenCL program '%s'.\n", PROGRAM_NAME);
    }

    // Build program
    //
    dev->program = clCreateProgramWithSource (dev->context, 1, &opencl_prog, NULL, &err);
    check (err, "Failed to create program");

    char options[OPENCL_PROG_MAX_STRING_SIZE_OPTIONS];

    // Tile size of 32 works better on Xeon/Xeon Phi
    //
    if(dev->type != CL_DEVICE_TYPE_GPU)
      dev->tile_size = 32;
    else
      dev->tile_size = TILE_SIZE;

#ifdef SLIDE
      dev->slide_steps = SLIDE;
#else
      dev->slide_steps = 1;
#endif

    sprintf (options,
	     OPENCL_BUILD_OPTIONS
	     "-DTILE_SIZE=%d "
	     "-DSUBCELL=%d "
             "-DDELTA_T=%.10f "
#ifdef SLIDE
	     "-DSLIDE=%d "
#endif
	     OPENCL_PROG_STRING_OPTIONS " -I "OCL_INCLUDE " "
	     LENNARD_STRING,
	     dev->tile_size,
	     SUBCELL,
             1.0f,
#ifdef SLIDE
	     dev->slide_steps,
#endif
	     OPENCL_PROG_PARAM_OPTIONS,
	     LENNARD_PARAM);

    // If not a GPU, do not use Tiling
    //
    if (dev->type != CL_DEVICE_TYPE_GPU)
      strcat (options, " -DNO_LOCAL_MEM");

#ifdef TILE_CACHE
    // On GPU, use a cache of TILES
    //
    if (dev->type == CL_DEVICE_TYPE_GPU)
      strcat (options, " -DTILE_CACHE");
#endif

    // Multi-accelerators configuration
    //
    if (sotl_have_multi())
      strcat (options, " -DHAVE_MULTI");

#ifdef FORCE_N_UPDATE
    if (!sotl_have_multi())
      strcat (options, " -DFORCE_N_UPDATE");
#endif

#ifdef TORUS
    strcat (options, " -DXY_TORUS -DZ_TORUS");
#endif

#ifdef XEON_VECTORIZATION
    strcat (options, " -DXEON_VECTORIZATION");
#endif

#if defined(__APPLE__)
    strcat(options, " -DHAVE_PRINTF");
#endif

    if (sotl_verbose)
      sotl_log(INFO, "--- Compiler flags ---\n%s\n----------------------\n",
               options);

    err = clBuildProgram (dev->program, 0, NULL, options, NULL, NULL);
    if(sotl_verbose || err != CL_SUCCESS) {
      size_t len;

      // Display compiler error log
      //
      clGetProgramBuildInfo (dev->program, dev->id,
			     CL_PROGRAM_BUILD_LOG, 0, NULL, &len);
        {
	  char buffer[len + 1];

	  clGetProgramBuildInfo (dev->program, dev->id,
				 CL_PROGRAM_BUILD_LOG,
				 sizeof (buffer), buffer, NULL);
	  sotl_log(INFO, "---- Compiler log ----\n%s\n----------------------\n",
		   buffer);
        }
        check (err, "Failed to build program");
    }

    // Create an OpenCL command queue
    //
    dev->queue = clCreateCommandQueue (dev->context, dev->id,
                CL_QUEUE_PROFILING_ENABLE, &err);
    check (err, "Failed to create a command queue");

    cl_create_kernels(dev);
}
Ejemplo n.º 27
0
int seg_usage_calc(struct back_storage* storage,uint32_t block_size,uint32_t segno,struct inode *refer_inode,SEG_USAGE_T *seg_usage)
{
    //HLOG_DEBUG("enter func %s",__func__);
    if(storage == NULL || refer_inode == NULL || seg_usage == NULL){
		HLOG_ERROR("input params failed");
		return -1;
    }
#if 0
	if(seg_usage->bitmap!=0 && segno != seg_usage->segno){
		HLOG_ERROR("segno not match");
		return -1;
	}	
#endif	
    int ret = 0;
    int log_idx=0;
    int idx;
    uint32_t offset = 0; 
    struct log_header *lh;
    //gchar **v = g_strsplit(segfile,".",2);
    // uint64_t db_mine_storage_addr_segno = atol(v[0]);
    //g_strfreev(v);

    GArray *tmp_bit_array;
    seg_usage->segno = segno; 
    seg_usage->timestamp = get_current_time();
    HLOG_DEBUG("seg usage's segno:%llu,timestamp:%llu",seg_usage->segno,seg_usage->timestamp);

    char segfile[SEGMENT_FILE_NAME_MAX];
	build_segfile_name(segno,segfile);
	char *content = NULL;
	uint32_t size;
	if(0!= (ret = file_get_contents(storage,segfile,&content,&size))){
	    HLOG_ERROR("read segfile:%s failed",segfile);
		return -1;
	}		

    tmp_bit_array = g_array_new(FALSE,FALSE,sizeof(gint));
	

    while(offset < size){
#if 0
        ret=storage->bs_file_pread(storage,file, (char*)&lh, LOG_HEADER_LENGTH, offset) ;//TODO read 64M once
        g_message("read content len:%d\n",ret);
        if(ret<0){
            ret = -1;
            goto out;
        }else if (ret == 0){
            g_message("read over?\n");
            ret = 0;
            break;
        }else if (ret == LOG_HEADER_LENGTH){
            g_message("read log header over\n");
            ;
        }else{
            g_message("read log header failed\n");
            ret = -1;
            goto out;
        }
#endif 
        lh = (struct log_header*)(content + offset);
        if(seg_usage->log_num !=0){
            //HLOG_DEBUG("this segfile:%s has calc",segfile);
            idx = log_idx/sizeof(gint);
            if(!(seg_usage->bitmap[idx] & (1<<(log_idx%sizeof(gint))))){
                log_idx++;
                int x=0;
                g_array_append_val(tmp_bit_array,x);
                offset += lh->log_size;
                continue;
            }
        }
        uint32_t orgine_alive_block_num = seg_usage->alive_block_num;
        //HLOG_DEBUG("start db no:%llu,db num:%d",lh->start_db_no,lh->db_num);
        int i;
#if 1 /* check refer inode whether still refer to given db in seg */
        for(i=0;i<lh->db_num;i++){
            //HLOG_DEBUG("for db:%llu",lh->start_db_no+i);
            uint64_t db_mine_storage_addr = 0;
            uint32_t db_mine_storage_addr_offset = offset + LOG_HEADER_LENGTH+i*block_size;
            set_offset(&db_mine_storage_addr,db_mine_storage_addr_offset);
            set_segno (&db_mine_storage_addr,segno);
            uint64_t db_cur_storage_addr = get_db_storage_addr_in_inode(storage,refer_inode,
			    						                                lh->start_db_no+i,block_size);
            HLOG_DEBUG("db:%llu's mine storage addr:%llu,cur storage addr:%llu",
			    	lh->start_db_no+i,db_mine_storage_addr,db_cur_storage_addr);
            if(db_mine_storage_addr != db_cur_storage_addr){
                HLOG_DEBUG("this is overwrite data block");
            }else{
                seg_usage->alive_block_num++;
                HLOG_DEBUG("this is used data block :%llu",seg_usage->alive_block_num);
            }
			seg_usage->block_num++;
        }
#endif
        //uint32_t alive_blocks = log_usage_calc(storage,latest_inode,&lh,db_mine_storage_addr_segno,offset,block_size);
        if(orgine_alive_block_num == seg_usage->alive_block_num){
            HLOG_DEBUG("log:%d has not any datablock",log_idx);
            //uint32_t bitmap_idx = log_idx / ALIVE_LOG_BITMAP ;
            //seg_usage->alive_log_bitmap[bitmap_idx] &= ~(1 << (log_idx % sizeof(uint64_t)));
            int x=0;
            g_array_append_val(tmp_bit_array,x);
        }else{
            HLOG_DEBUG("log:%d has any datablock",log_idx);
            int x=1;
            g_array_append_val(tmp_bit_array,x);
        }
        offset += lh->log_size;
        log_idx++;    
    }

    int i;
    seg_usage->log_num = tmp_bit_array->len;
    g_free(seg_usage->bitmap);
    seg_usage->bitmap = (char*)g_malloc0((seg_usage->log_num-1)/sizeof(gint)+1);
    //HLOG_DEBUG("size of bitmap:%d",tmp_bit_array->len);
    for(i=0;i<tmp_bit_array->len;i++){
        gint value = g_array_index(tmp_bit_array,gint,i);
        idx = i/sizeof(gint);
        if(value==1){
           //g_message("bitmap idx bit:%d = 1\n",i);
           seg_usage->bitmap[idx] |= 1<<i%sizeof(gint);
           //g_message("bitmap idx %x\n",seg_usage->bitmap[idx]);
       }
    }
    g_array_free(tmp_bit_array,TRUE);
	//HLOG_DEBUG("leave func %s",__func__);
    return 0;
}
Ejemplo n.º 28
0
DWORD CFileDownloader::Download( LPCTSTR lpszURL, LPCTSTR lpszFilename, LPCTSTR lpszRefererUrl, LPVOID pUserData, BOOL bUseCache, BOOL bUseProxyConfig )
{
	m_Stopped = FALSE;
	if(!SplitDownloadUrl( lpszURL, m_strHostname, m_strHostPath, m_strHostFilename ))
		return FALSE;
	
	m_pUserData = pUserData;
	m_strDownloadURL = lpszURL;
	m_strDownloadFile = lpszFilename;

	// Check the tmp file 
	m_strDownloadFileTemp = m_strDownloadFile + _T(".tmp");
	m_strDownloadFileInfo = m_strDownloadFile + _T(".nfo");		
	
	// Check if file exists 
	if( bUseCache && IsFileExist(m_strDownloadFile) )
	{
		return TRUE;
	}
	else if(!bUseCache)
	{
		DeleteFile(m_strDownloadFileTemp);
		DeleteFile(m_strDownloadFileInfo);
		DeleteFile(m_strDownloadFile);
	}
	
	CPubConfig::T_ProxySetting proxyconfig;
	CPubConfig pubconfig;
	pubconfig.LoadProxyConfig(proxyconfig);	
	SetProxySetting(proxyconfig);


	INT64 lContentSize = 0;
	INT64 lFileSize = 0;
	if( IsFileExist(m_strDownloadFileTemp) && IsFileExist(m_strDownloadFileInfo) )
	{
		CString strLastModified;
		BOOL notModified = FALSE;
		if( file_get_contents(m_strDownloadFileInfo, strLastModified) )		
		{
			LPCTSTR lpszLengthTag = _T("; length=");
			LPCTSTR pszLen = _tcsstr(strLastModified, lpszLengthTag);
			if(pszLen)
			{
				pszLen+= _tcslen(lpszLengthTag);
				lContentSize = _ttoi64(pszLen);
			}

			// 检查文件是否完全下载完成了 
			lFileSize = file_get_size( m_strDownloadFileTemp );
			if(lFileSize>0 && lFileSize==lContentSize)
			{
				MoveFile(m_strDownloadFileTemp, m_strDownloadFile);
				DeleteFile(m_strDownloadFileInfo);
				return TRUE;
			}

			if( _CheckIfModifiedSince(lpszURL, strLastModified, bUseProxyConfig, notModified) && notModified )
			{
			}
			else
			{
				lFileSize = 0;
			}
		}
	}
	// 如果文件已经过期, 或者文件的信息文件不存在, 都删除旧下载临时文件 
	if(lFileSize==0)
	{
		DeleteFile(m_strDownloadFileTemp);
		DeleteFile(m_strDownloadFileInfo);
	}
	
	// Prepare file 
	_CloseFileHandler();
	m_hFile = CreateFile(m_strDownloadFileTemp, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if( m_hFile==INVALID_HANDLE_VALUE )
		return FALSE;
	SetFilePointer( m_hFile, lFileSize, 0, FILE_BEGIN );
	
	if(m_pBuffer==NULL)
		m_pBuffer = new BYTE[HTTP_BUFFER_SIZE];	
	INT nRetry = HTTP_DEFAULT_RETYR;
	INT nRetried = 0;
	do 
	{
		INT iRet = _DownloadFileFrom(lFileSize, lContentSize, bUseProxyConfig);
		DEBUG_TRACE(_T("FD:_DownloadFileFrom %I64d/%I64d LastError:%d Ret:%d"), lFileSize, lContentSize, GetLastError(), iRet);
		_Cleanup();

		if(iRet>0)
		{
			// 考虑socket 被主动关闭 
			if(lFileSize>=lContentSize)
				break;
			nRetry = HTTP_DEFAULT_RETYR;
		}
		else if(iRet==0)
		{
			--nRetry;
		}
		else if(iRet==-1)
		{
			// 文件长度不匹配! 需要删了文件, 然后重新下载 
			_CloseFileHandler();
			DeleteFile(m_strDownloadFileTemp);
			DeleteFile(m_strDownloadFileInfo);
			lFileSize = lContentSize = 0;
			
			m_hFile = CreateFile(m_strDownloadFileTemp, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if( m_hFile==INVALID_HANDLE_VALUE )
				break;
			--nRetry;
		}
		else if(iRet==-2)
		{
			// 写入文件失败, 直接返回
			break;
		}
		else
		{
			ATLASSERT(FALSE);
			break;
		}
		++ nRetried;
	} while (!m_Stopped && nRetry>0 && nRetried<HTTP_DEFAULT_MAXRETYR);
	
	_CloseFileHandler();
	BOOL bFileDone = FALSE;
	if(lContentSize==0)
	{
		// 163.com 等页面
		if(lFileSize==0)
		{
			DeleteFile(m_strDownloadFileTemp);
		}
		else if(!m_Stopped)
		{
			bFileDone = TRUE;
		}
	}
	else
	{
		bFileDone = lFileSize>=lContentSize;
	}
	if(bFileDone)
	{
		MoveFile(m_strDownloadFileTemp, m_strDownloadFile);
		DeleteFile(m_strDownloadFileInfo);
	}
	BOOL bRet = PathFileExists(m_strDownloadFile);
	_FireFileDownloaderEvent(bRet ? IFileDownloaderObserver::DOWNLOAD_COMPLETE : IFileDownloaderObserver::DOWNLOAD_ERROR);
	return bRet;
}
Ejemplo n.º 29
0
/**
 Evaluates the given TAN-TPV WCS header on a grid of points,
 fitting a SIP distortion solution to it.

 The grid can be specified by either:

 double* xy, int Nxy

 double stepsize=100, double xlo=0, double xhi=0, double ylo=0, double yhi=0

 xlo and xhi, if both 0, default to 1. and the WCS width
 ylo and yhi, if both 0, default to 1. and the WCS height

 The number of steps is chosen to be the closest step size to split the range
 xlo to xhi into an integer number of steps.

 imageW and imageH, if non-zero, override the image width read from the WCS,
 and ALSO the WCS width/height mentioned above.

 */
int wcs_pv2sip(const char* wcsinfn, int ext,
			   const char* wcsoutfn,
			   anbool scamp_head_file,

			   double* xy, int Nxy,
               
               double stepsize,
               double xlo, double xhi,
               double ylo, double yhi,

			   int imageW, int imageH,
               int order,
			   anbool forcetan,
               int doshift) {

	qfits_header* hdr = NULL;
    sip_t* sip = NULL;
    int rtn = -1;

	if (scamp_head_file) {
		size_t sz = 0;
		char* txt;
		char* prefix;
		int np;
		int nt;
		unsigned char* txthdr;
		sl* lines;
		int i;
		txt = file_get_contents(wcsinfn, &sz, TRUE);
		if (!txt) {
			ERROR("Failed to read file %s", wcsinfn);
			goto bailout;
		}
		lines = sl_split(NULL, txt, "\n");
		prefix =
			"SIMPLE  =                    T / Standard FITS file                             "
			"BITPIX  =                    8 / ASCII or bytes array                           "
			"NAXIS   =                    0 / Minimal header                                 "
			"EXTEND  =                    T / There may be FITS ext                          "
			"WCSAXES =                    2 /                                                ";
		np = strlen(prefix);
		nt = np + FITS_LINESZ * sl_size(lines);
		txthdr = malloc(nt);
		memset(txthdr, ' ', np + FITS_LINESZ * sl_size(lines));
		memcpy(txthdr, prefix, np);
		for (i=0; i<sl_size(lines); i++)
			memcpy(txthdr + np + i*FITS_LINESZ, sl_get(lines, i), strlen(sl_get(lines, i)));
		sl_free2(lines);
		hdr = qfits_header_read_hdr_string(txthdr, nt);
		free(txthdr);
		free(txt);
	} else {
		hdr = anqfits_get_header2(wcsinfn, ext);
    }
	if (!hdr) {
		ERROR("Failed to read header: file %s, ext %i\n", wcsinfn, ext);
		goto bailout;
	}

    sip = wcs_pv2sip_header(hdr, xy, Nxy, stepsize, xlo, xhi, ylo, yhi,
                            imageW, imageH, order, forcetan, doshift);
    if (!sip) {
        goto bailout;
    }
    sip_write_to_file(sip, wcsoutfn);

	rtn = 0;

 bailout:
	qfits_header_destroy(hdr);
	return rtn;
}
Ejemplo n.º 30
0
int wcs_pv2sip(const char* wcsinfn, int ext,
			   const char* wcsoutfn,
			   anbool scamp_head_file,
			   double* xy, int Nxy,
			   int imageW, int imageH,
			   anbool forcetan) {
	qfits_header* hdr = NULL;
	double* radec = NULL;
	int rtn = -1;
	tan_t tanwcs;
	double x,y, px,py;
	double xyz[3];

	double* xorig = NULL;
	double* yorig = NULL;
	double* rddist = NULL;
	int i, j;

	//           1  x  y  r x2 xy y2 x3 x2y xy2 y3 r3 x4 x3y x2y2 xy3 y4
	//          x5 x4y x3y2 x2y3 xy4 y5 r5 x6 x5y x4y2, x3y3 x2y4 xy5 y6
	//          x7 x6y x5y2 x4y3 x3y4 x2y5 xy6 y7 r7
	int xp[] = { 0, 1, 0, 0, 2, 1, 0, 3,  2,  1, 0, 0, 4,  3,   2,  1, 0,
				 5,  4,   3,   2,  1, 5, 0, 6,  5,   4,    3,   2,  1, 0,
				 7,  6,   5,   4,   3,   2,  1, 0, 0};
	int yp[] = { 0, 0, 1, 0, 0, 1, 2, 0,  1,  2, 3, 0, 0,  1,   2,  3, 4,
				 0,  1,   2,   3,  4, 0, 0, 0,  1,   2,    3,   4,  5, 6,
				 0,  1,   2,   3,   4,   5,  6, 7, 0};
	int rp[] = { 0, 0, 0, 1, 0, 0, 0, 0,  0,  0, 0, 3, 0,  0,   0,  0, 0,
				 0,  0,   0,   0,  0, 0, 5, 0,  0,   0,    0,   0,  0, 0,
				 0,  0,   0,   0,   0,   0,  0, 0, 7};
	double xpows[8];
	double ypows[8];
	double rpows[8];
	double pv1[40];
	double pv2[40];
	double r;

	if (scamp_head_file) {
		size_t sz = 0;
		char* txt;
		char* prefix;
		int np;
		int nt;
		unsigned char* txthdr;
		sl* lines;
		int i;
		txt = file_get_contents(wcsinfn, &sz, TRUE);
		if (!txt) {
			ERROR("Failed to read file %s", wcsinfn);
			goto bailout;
		}
		lines = sl_split(NULL, txt, "\n");
		prefix =
			"SIMPLE  =                    T / Standard FITS file                             "
			"BITPIX  =                    8 / ASCII or bytes array                           "
			"NAXIS   =                    0 / Minimal header                                 "
			"EXTEND  =                    T / There may be FITS ext                          "
			"WCSAXES =                    2 /                                                ";
		np = strlen(prefix);
		nt = np + FITS_LINESZ * sl_size(lines);
		txthdr = malloc(nt);
		memset(txthdr, ' ', np + FITS_LINESZ * sl_size(lines));
		memcpy(txthdr, prefix, np);
		for (i=0; i<sl_size(lines); i++)
			memcpy(txthdr + np + i*FITS_LINESZ, sl_get(lines, i), strlen(sl_get(lines, i)));
		sl_free2(lines);
		hdr = qfits_header_read_hdr_string(txthdr, nt);
		free(txthdr);
		free(txt);
	} else {
		char* ct;
		hdr = anqfits_get_header2(wcsinfn, ext);

		ct = fits_get_dupstring(hdr, "CTYPE1");
		if ((ct && streq(ct, "RA---TPV")) || forcetan) {
			// http://iraf.noao.edu/projects/ccdmosaic/tpv.html
			logmsg("Replacing CTYPE1 = %s header with RA---TAN\n", ct);
			fits_update_value(hdr, "CTYPE1", "RA---TAN");
		}
		ct = fits_get_dupstring(hdr, "CTYPE2");
		if ((ct && streq(ct, "DEC--TPV")) || forcetan) {
			logmsg("Replacing CTYPE2 = %s header with DEC--TAN\n", ct);
			fits_update_value(hdr, "CTYPE2", "DEC--TAN");
		}
	}
	if (!hdr) {
		ERROR("Failed to read header: file %s, ext %i\n", wcsinfn, ext);
		goto bailout;
	}
	
	tan_read_header(hdr, &tanwcs);

	for (i=0; i<sizeof(pv1)/sizeof(double); i++) {
		char key[10];
		sprintf(key, "PV1_%i", i);
		pv1[i] = qfits_header_getdouble(hdr, key, 0.0);
		sprintf(key, "PV2_%i", i);
		pv2[i] = qfits_header_getdouble(hdr, key, 0.0);
	}

	xorig = malloc(Nxy * sizeof(double));
	yorig = malloc(Nxy * sizeof(double));
	rddist = malloc(2 * Nxy * sizeof(double));

	for (j=0; j<Nxy; j++) {
		xorig[j] = xy[2*j+0];
		yorig[j] = xy[2*j+1];

		tan_pixelxy2iwc(&tanwcs, xorig[j], yorig[j], &x, &y);
		r = sqrt(x*x + y*y);
		xpows[0] = ypows[0] = rpows[0] = 1.0;
		for (i=1; i<sizeof(xpows)/sizeof(double); i++) {
			xpows[i] = xpows[i-1]*x;
			ypows[i] = ypows[i-1]*y;
			rpows[i] = rpows[i-1]*r;
		}
		px = py = 0;
		for (i=0; i<sizeof(xp)/sizeof(int); i++) {
			px += pv1[i] * xpows[xp[i]] * ypows[yp[i]] * rpows[rp[i]];
			py += pv2[i] * ypows[xp[i]] * xpows[yp[i]] * rpows[rp[i]];
		}
		tan_iwc2xyzarr(&tanwcs, px, py, xyz);
		xyzarr2radecdeg(xyz, rddist+2*j, rddist+2*j+1);
	}

	//
	{
		starxy_t sxy;
		tweak_t* t;
		il* imgi;
		il* refi;
		int sip_order = 5;
		int sip_inv_order = 5;

		sxy.N = Nxy;
		sxy.x = xorig;
		sxy.y = yorig;

		imgi = il_new(256);
		refi = il_new(256);
		for (i=0; i<Nxy; i++) {
			il_append(imgi, i);
			il_append(refi, i);
		}

		t = tweak_new();
		t->sip->a_order = t->sip->b_order = sip_order;
		t->sip->ap_order = t->sip->bp_order = sip_inv_order;
		tweak_push_wcs_tan(t, &tanwcs);
		tweak_push_ref_ad_array(t, rddist, Nxy);
		tweak_push_image_xy(t, &sxy);
		tweak_push_correspondence_indices(t, imgi, refi, NULL, NULL);
		tweak_go_to(t, TWEAK_HAS_LINEAR_CD);
		if (imageW)
			t->sip->wcstan.imagew = imageW;
		if (imageH)
			t->sip->wcstan.imageh = imageH;
		sip_write_to_file(t->sip, wcsoutfn);
		tweak_free(t);
	}
	rtn = 0;

 bailout:
	free(xorig);
	free(yorig);
	free(rddist);
	qfits_header_destroy(hdr);
	free(radec);
	return rtn;
}