Exemplo n.º 1
0
int main(int argc, char **argv) {
	if (argc != 2) {
		fprintf(stderr, "Usage: ./parhist <filename>\n");
		exit(1);
	}

	const char *filename = argv[1];

	// create a memory-mapped view of the file
	size_t file_size = get_file_size(filename);
	struct mmap_region region;
	map_file_region(filename, file_size, &region);

	// This is the array of values and the number of elements
	uint16_t *arr = region.addr;
	size_t num_elements = file_size/sizeof(uint16_t);

	// This is the histogram: each element counts the number
	// of data values that fell into a particular 4000-wide range:
	// Histogram element 0 counts number of values from 1..4000
	// Histogram element 1 counts number of values from 4001..8000
	// etc.
	int histogram[NUM_BUCKETS] = { 0 };

	// Sequential computation
	for (size_t i = 0; i < num_elements; i++) {
		uint16_t val = arr[i];
		int bucket = (val-1)/BUCKET_SIZE;
		if (bucket < 0) {
			bucket = 0;
		} else if (bucket >= NUM_BUCKETS) {
			bucket = NUM_BUCKETS-1;
		}
		histogram[bucket]++;
	}

	// Print histogram
	for (int i = 0; i < NUM_BUCKETS; i++) {
		printf("%5i..%5i: %i\n", i*BUCKET_SIZE+1, (i+1)*BUCKET_SIZE, histogram[i]);
	}

	return 0;
}
Exemplo n.º 2
0
void print_working_dir(pDataStruct workingData){
	pNode temp = workingData->workingDir->directoryHeadNode;
	printf("Type  Size     Date     Name       Perms\n_______________________________________\n");//40_
	while ( temp != NULL ){
		if(temp->type == FILE){
			printf("FILE @d  @x   @s  ",get_file_size(temp->file), temp->date, temp->name);
			print_perms(temp,workingData);
			printf("\n");
		}
		if(temp->type == DIRECTORY){
			printf("DIR  @d  @x   @s ",sizeof(sNode), temp->date, temp->name);
			print_perms(temp,workingData);
			printf("\n");
		}

		temp = temp->next;

	}
}
Exemplo n.º 3
0
    CXSourceRange get_range_whole_file() const
    {
        size_t const file_size = get_file_size(file_name.c_str());
        CXFile const file = clang_getFile(translation_unit, file_name.c_str());

        auto const file_begin = clang_getLocationForOffset(translation_unit, file, 0);
        auto const file_end = clang_getLocationForOffset(translation_unit, file, file_size);

        if(is_null_location(file_begin) || is_null_location(file_end)) {
            return clang_getNullRange();
        }

        auto const file_range = clang_getRange(file_begin, file_end);
        if(clang_Range_isNull(file_range)) {
            return clang_getNullRange();
        }

        return file_range;
    }
Exemplo n.º 4
0
static ssize_t _log_write(struct iovec *vec, int n)
{
    unsigned long long tmp_size = get_file_size(_log_name);
    if (UNLIKELY(tmp_size > _log_file_size)) {
        fprintf(stderr, "%s size= %llu reach max %llu, splited\n",
                _log_name, tmp_size, _log_file_size);
        if (-1 == _log_close()) {
            fprintf(stderr, "_log_close errno:%d", errno);
        }
        log_get_time(_log_name_time, sizeof(_log_name_time), 1);
        snprintf(_log_name, sizeof(_log_name), "%s%s_%s",
                _log_path, _log_name_prefix, _log_name_time);

        _log_open(_log_name);
        fprintf(stderr, "splited file %s\n", _log_name);
    }

    return writev(_log_fd, vec, n);
}
Exemplo n.º 5
0
//	添加识别关键词语,开发者可以学习"语音识别芯片LD3320高阶秘籍.pdf"中关于垃圾词语吸收错误的用法
uint8 LD_AsrAddFixed(char cmd)	  //添加关键词语到LD3320芯片中
{
	//先检查传入的文件名是否符合规范
	char i;
	for(i=0;i<=LD_struct_index;i++)
		{
		rt_kprintf("添加用户码:%d 指令: %s  播放音乐:%s 配置文件:%s 执行动作:%s  \r\n",ld_struct[i].pCode,ld_struct[i].sRecog,ld_struct[i].mp3_name,ld_struct[i].next_ini,ld_struct[i].action);
	LD_AsrAddFixed_ByString(ld_struct[i].sRecog,ld_struct[i].pCode);
		}
			wu_fd = open(Name_ini,0,0);
		i = get_file_size(wu_fd);
	read(wu_fd, line_data, sizeof(line_data));
		line_data[i]='\0';
		close(wu_fd);
		rt_kprintf("添加用户码: 49 用户名: %s  \r\n",line_data);
		LD_AsrAddFixed_ByString(line_data,49);  //添加用户名
	return 1;

}
Exemplo n.º 6
0
void fetch_fd_file(pid_t pid, int flags, int fd, int inode, char *fd_path,
	struct cp_file *file)
{
    int bufsz = 512;
    int retsz;
    char *buf = NULL;

    file->filename = NULL;
    file->deleted = 0;
    file->size = get_file_size(pid, fd);
    file->contents = NULL;

    do {
	buf = xmalloc(bufsz);
	retsz = readlink(fd_path, buf, bufsz);
	if (retsz <= 0) {
	    fprintf(stderr, "Error reading FD %d: %s\n", fd, strerror(errno));
	    goto out;
	} else if (retsz < bufsz) {
	    /* Read was successful */
	    buf[retsz] = '\0';
	    file->filename = strdup(buf);
	    break;
	}
	/* Otherwise, double the buffer size and try again */
	free(buf);
	bufsz <<= 1;
    } while (bufsz <= 8192); /* Keep it sane */

    bufsz = strlen(file->filename);
    if (bufsz > 10 && strcmp(" (deleted)", file->filename+bufsz-10) == 0) {
	file->deleted = 1;
	*(file->filename+bufsz-10) = '\0';
	file->contents = xmalloc(file->size);
	if (!scrape_contents(pid, fd, file->size, file->contents)) {
	    xfree(file->contents);
	    file->contents = NULL;
	}
    }
out:
    free(buf);
}
Exemplo n.º 7
0
int decode(std::string file_path, std::string &decode_content)
{
	BYTE init_array[16] = {0}; 
	FILE *data_file = fopen(file_path.c_str(), "rb");

	if (data_file == NULL)
	{
		return -1;
	}

	size_t file_size = get_file_size(data_file);
	BYTE *file_buffer = new BYTE[file_size];
	fread(file_buffer, 1, file_size, data_file);
	fclose(data_file);
    //_maxthon3_default_storage_
	//Maxthon3_MxCmpUrl_Mood
	//Maxthon__WebSIteBooster
	//guestmaxthon3_favdb_txmood
	//guestmaxthon3_config_txmood
	//username+maxthon3_favdb_txmood

	HCRYPTKEY hCryptKey = CreateKey((BYTE *)"guestmaxthon3_favdb_txmood", 0x1a);

	for (int page_index = 0; page_index < file_size / PAGE_SIZE; page_index++)
	{
		DWORD dwPageSize = PAGE_SIZE;
		BYTE *page_content = &file_buffer[page_index * PAGE_SIZE];

		CryptDecrypt(hCryptKey, 0, 1, 0, page_content, &dwPageSize);
	
	}

	FILE *fOut = fopen("maxthon_a.db", "wb");

	fwrite(file_buffer, 1, file_size, fOut);

	decode_content.assign((char *)file_buffer, file_size);

	fclose(fOut);

	return 0;
}
Exemplo n.º 8
0
static void write_syslog(char *fmt,...)
{
	va_list argptr;
	//int cnt = 0;
	char buffer[1024] = {0};
	FILE *fp = NULL;
	time_t			t = time(NULL);
	struct tm		timet;

	if (get_file_size(GMI_LOG_FILE) < GMI_LOG_MAX_SIZE)
	{
		//append log to the end of file
		fp = fopen(GMI_LOG_FILE, "a+" );
	}
	else
	{
		//create a new file to write log
		fp = fopen(GMI_LOG_FILE, "wb" );
	}

	if(fp == NULL ) 
	{
		printf("fopen error\n");         
		return ;
	} 

	//write time info
	memset(buffer, 0, sizeof(buffer));
	localtime_r(&t, &timet);
	snprintf(buffer, sizeof(buffer) - 1, "%04d-%02d-%02d %02d:%02d:%02d\n", timet.tm_year + 1900, timet.tm_mon + 1, timet.tm_mday, timet.tm_hour, timet.tm_min, timet.tm_sec);
	fwrite(buffer, strlen(buffer), 1, fp);

	//write log msg
	memset(buffer, 0, sizeof(buffer));
	va_start(argptr, fmt);
	vsnprintf(buffer, sizeof(buffer) - 1, fmt, argptr);
	va_end(argptr);
	fwrite(buffer, strlen(buffer), 1, fp);
	fflush(fp);
	fclose(fp);
	fp = NULL;
}
Exemplo n.º 9
0
/* Steem Engine cartridge image */
static int cmd_stc(FILE* infile, const char* infilename,
                   FILE* outfile, const char* outfilename)
{
    size_t source_size;
    size_t target_size = 128 * 1024;
    size_t free_size;
    int ret; /* boolean return value: 0 == error, 1 == OK */

    printf("# Padding %s to %ld kB Steem Engine cartridge image into %s\n", infilename, ((long)target_size) / 1024, outfilename);

    /* Get the input file size */
    source_size = get_file_size(infile, infilename);
    if (source_size == SIZE_ERROR)
        return 0;

    /* Check if the input file size is not too big */
    if (source_size > target_size)
    {
        fprintf(stderr, "%s: %s is too big: %lu extra bytes\n", g_argv0, infilename, (unsigned long)(source_size - target_size));
        return 0;
    }

    /* Insert a long zero at the beginning */
    ret = write_byte_block(outfile, outfilename, 0, 4);
    if (!ret)
        return ret;

    /* Copy the input file */
    ret = copy_stream(infile, infilename, outfile, outfilename, source_size);
    if (!ret)
        return ret;

    /* Pad with zeroes */
    free_size = target_size - source_size;
    ret = write_byte_block(outfile, outfilename, 0, free_size);
    if (!ret)
        return ret;

    printf("# %s done (%lu bytes free)\n", outfilename, (unsigned long)free_size);

    return 1;
}
Exemplo n.º 10
0
/**
 * @brief Read a file into memory and returns a pointer to it
 * @param char * filename
 * @return char * ptr
 */
char * readFile(char * filename)
{
    int file, length;
    char * ptr; /* Contents of json file */
    if((file = open(filename, O_RDONLY, 0)) == -1){
        return NULL;
    }

    length = get_file_size(file);

    if((ptr = malloc(length * sizeof(char) )) == NULL){
        return NULL;
    }
    //TODO: Make sure everything is read?
    if(read(file, ptr, length) == -1){
        return NULL;
    }
    close(file);
    return ptr;
}
Exemplo n.º 11
0
// write the master hash table
void write_master_hash_table(FILE *f)
{
    unsigned int i = 1;
    unsigned int off, blockoff;
    unsigned int filesize = get_file_size(f);

    off = SECOND_HASH_START;
    blockoff = BLOCK_HASH_START;
    write_hash(f, off, blockoff, BLOCK_SIZE, 1);

    while(1)
    {
        off = SECOND_HASH_START + i * 24;
        blockoff = FILE_START_OFFSET + (0xAA * BLOCK_SIZE * i) + (BLOCK_SIZE * (i-1));
        if (blockoff > (filesize-1)) break;

        write_hash(f, off, blockoff, BLOCK_SIZE, 0);
        i++;
    }
}
Exemplo n.º 12
0
/**
 * Loads snt offsets from the given binary file.
 */
vector_int* load_snt_offsets(const char* name) {
U_FILE* f=u_fopen(BINARY,name,U_READ);
if (f==NULL) return NULL;
long size=get_file_size(f);
if (size%(3*sizeof(int))!=0) {
	u_fclose(f);
	return NULL;
}
vector_int* v=new_vector_int((int)(size/sizeof(int)));
if (size!=0) {
	int n=(int)fread(v->tab,sizeof(int),size/sizeof(int),f);
	u_fclose(f);
	if (n!=(int)(size/sizeof(int))) {
		free_vector_int(v);
		return NULL;
	}
	v->nbelems=v->size;
}
return v;
}
Exemplo n.º 13
0
static rc_t vdb_info_1( VSchema * schema, dump_format_t format, const VDBManager *mgr,
                        const char * acc_or_path, const char * table_name )
{
    rc_t rc = 0;
    vdb_info_data data;

    memset( &data, 0, sizeof data );
    data.s_platform = PT_NONE;
    data.acc = acc_or_path;

    /* #1 get path-type */
    data.s_path_type = get_path_type( mgr, acc_or_path );

    if ( data.s_path_type[ 0 ] == 'D' || data.s_path_type[ 0 ] == 'T' )
    {
        rc_t rc1;

        /* #2 fork by table or database */
        switch ( data.s_path_type[ 0 ] )
        {
            case 'D' : vdb_info_db( &data, schema, mgr ); break;
            case 'T' : vdb_info_tab( &data, schema, mgr ); break;
        }

        rc1 = resolve_accession( acc_or_path, data.path, sizeof data.path, false );
        if ( rc1 == 0 )
            data.file_size = get_file_size( data.path );

        switch ( format )
        {
            case df_xml  : rc = vdb_info_print_xml( &data ); break;
            case df_json : rc = vdb_info_print_json( &data ); break;
            case df_csv  : rc = vdb_info_print_sep( &data, ',' ); break;
            case df_tab  : rc = vdb_info_print_sep( &data, '\t' ); break;
            case df_sql  : rc = vdb_info_print_sql( table_name, &data ); break;
            default     : rc = vdb_info_print_dflt( &data ); break;
        }
    }

    return rc;
}
Exemplo n.º 14
0
static void
hexify_file (char *filename, char *target)
{
  bfd *abfd;
  char *dot;
  char *hex_file;

  if (get_file_size (filename) < 1)
    return;

  abfd = bfd_openr (filename, target);
  if (abfd == NULL)
    {
      nonfatal (filename);
      return;
    }

  if (bfd_check_format (abfd, bfd_object))
    {
      if (verbose)
        printf ("\n");

      /* strip extension from filename if present */
      dot = strrchr (filename, '.');
      if (dot)
        dot[0] = '\0';

      /* create a new name with .hex extension */
      hex_file = malloc (strlen (filename) + strlen (".hex") + 1);
      sprintf (hex_file, "%s%s", filename, ".hex");

      exit_status = write_hex_file (hex_file, abfd);

      if (verbose)
        printf ("\n");

      free (hex_file);
    }

  bfd_close (abfd);
}
/*--------------------------------------------------------------------------------*/
Data *read_gbt(const char *fname)
{
  Data *dat=(Data *)malloc(sizeof(Data));
  memset(dat,0,sizeof(Data));
  int nchan=4096;
  int npol=4;
  long ndat=get_file_size(fname);
  if (ndat<=0) {
    printf("FILE %s unavailable for reading.\n",fname);
    return NULL;
  }
  int nsamp=ndat/npol/nchan;
  printf("have %d samples.\n",nsamp);
  char **mat=cmatrix(nsamp,nchan);
  char *tmp=(char *)malloc(sizeof(char)*nchan*npol);
  FILE *infile=fopen(fname,"r");
  for (int i=0;i<nsamp;i++) {
    size_t nread=fread(tmp,sizeof(char),nchan*npol,infile);
    memcpy(mat[i],tmp,sizeof(char)*nchan);
  }
  fclose(infile);
  free(tmp);
  dat->raw_nchan=nchan;
  dat->ndata=nsamp;
  //dat->raw_data=mat;
  dat->raw_data=matrix(nchan,nsamp);
  for (int i=0;i<nchan;i++)
    for (int j=0;j<nsamp;j++)
      dat->raw_data[i][j]=mat[j][i];
  
  dat->raw_chans=(float *)malloc(sizeof(float)*dat->raw_nchan);
  dat->dt=1e-3;
  float dnu=(900-700.0)/dat->raw_nchan;
  for (int i=0;i<dat->raw_nchan;i++) {
    dat->raw_chans[i]=900-(0.5+i)*dnu;
  }

  free(mat[0]);
  free(mat);
  return dat;
}
Exemplo n.º 16
0
/*  Main function prints file size of self in bytes or argv[1] if supplied.
    Works only for regular files.
*/
int main( int argc, char *argv[] ) {
    long file_size = 0L;
    char *file_path;

    if ( argc == 2 ) {
        file_path = argv[1];
    }
    else {
        file_path = argv[0];
    }

    file_size = get_file_size( file_path );

    if ( file_size < 0 ) {
        local_perror();
        return 0;
    }

    printf("File size of file %s is %ld bytes\n", file_path, file_size);
    return 0;
}
Exemplo n.º 17
0
int erase_usercalibration_partition() {
    Volume *v = volume_for_path(USERCALIB_PATH);
    if (v == NULL) {
        // most devices won't have /mnt/usercalib, so this is not an error.
        return 0;
    }

    int fd = open(v->blk_device, O_RDWR);
    uint64_t size = get_file_size(fd);
    if (size != 0) {
        if (wipe_block_device(fd, size)) {
            LOGE("error wiping /mnt/usercalib: %s\n", strerror(errno));
            close(fd);
            return -1;
        }
    }

    close(fd);

    return 0;
}
Exemplo n.º 18
0
int main()
{
	int a;
	long size;
	FILE *pFile;
	pFile = fopen("text.txt", "r");
	if (pFile == NULL)
	{
		printf("Error while opening file\n");
		system("PAUSE");
		return 1;
	}
	size = get_file_size(pFile);
	printf("File size = %d\n", size);
	fclose(pFile);
	a = get_file_lines_count("Text.txt");
	printf("Lines count = %d\n", a);
	printf("s=%d\n", summAn(0, 3, 2));
	system("PAUSE");
	return 0;
}
Exemplo n.º 19
0
int read_input_file() {
  int directory_id = 0;
  int entry_id = 0;
  int cluster_id = 0;
  int file_size = 0;

  if (resolve_argument_path(argument[ARGUMENT_HEAP_SIZE-1], argument, resolve_result) == -1) {
    return -1;
  }
  directory_id = resolve_result[0];
  entry_id     = resolve_result[1];
  cluster_id   = resolve_result[2];

  file_size = get_file_size(directory_id, entry_id);
  if (file_size >= 1024) {
    error(TOO_MANY_INPUT);
  }
  read_file(cluster_id, file_size, input);

  return 0;
}
Exemplo n.º 20
0
/*
 * Add a file to the archive in RAM
 *
 * path: path to the file to be added
 * entry: pointer to struct dentry where file header is created
 * offset: offset of the file contents from the archive header
 *
 * return: 0 on success or -1 on error
 */
static int add_file(const char *path, struct dentry *entry, uint32_t offset)
{
	FILE *fp;
	int size;

	if (!path || !*path || !entry) {
		fprintf(stderr, "Error: invalid path or entry\n");
		return -1;
	}

	size = get_file_size(path);
	if (size < 0)
		return -1;
	if (offset + size > archive->size) {
		fprintf(stderr, "Error: invalid offset or size\n");
		return -1;
	}

	fp = fopen(path, "rb");
	if (!fp) {
		fprintf(stderr, "Error: failed to open %s (%d: %s)\n",
			path, errno, strerror(errno));
		return -1;
	}
	if (fread((char *)archive + offset, sizeof(char), size, fp) != size) {
		fprintf(stderr, "Error: failed to read %s\n", path);
		fclose(fp);
		return -1;
	}
	fclose(fp);

	/* set file name*/
	if (set_file_name(path, entry))
		return -1;

	entry->offset = offset;
	entry->size = size;

	return 0;
}
static void
list__process_line (char     *line,
		    gpointer  data)
{
	FrCommand  *comm = FR_COMMAND (data);
	FileData   *fdata;
	char      **fields;
	char       *filename;

	fdata = file_data_new ();

	fields = split_line (line, 2);
	if (strcmp (fields[1], "-1") != 0)
		fdata->size = g_ascii_strtoull (fields[1], NULL, 10);
	g_strfreev (fields);

	if (fdata->size == 0)
		fdata->size = get_file_size (comm->filename);

	filename = get_uncompressed_name_from_archive (comm, comm->filename);
	if (filename == NULL)
		filename = remove_extension_from_path (comm->filename);

	fdata->full_path = g_strconcat ("/",
					file_name_from_path (filename),
					NULL);
	g_free (filename);

	fdata->original_path = fdata->full_path + 1;
	fdata->link = NULL;
	fdata->modified = get_file_mtime_for_path (comm->filename);

	fdata->name = g_strdup (file_name_from_path (fdata->full_path));
	fdata->path = remove_level_from_path (fdata->full_path);

	if (*fdata->name == 0)
		file_data_free (fdata);
	else
		fr_command_add_file (comm, fdata);
}
Exemplo n.º 22
0
struct command *next_cmd()
{
	struct command *cmd;
	struct xmlNode *tmp;
	char *ptr = NULL;

	for(; cmd_list; cmd_list = cmd_list->next)
	{
                if (cmd_list->type != XML_ELEMENT_NODE)
                        continue;
                if (strcasecmp(cmd_list->name, "cmd") != 0)
                        continue;

		cmd = malloc(sizeof(struct command));
		memset(cmd, 0, sizeof(struct command));

		if (strcasecmp(xmlGetProp(cmd_list, "state"), "bootstrap") == 0)
			cmd->state = NULL; //need to take care of this
		else
			cmd->state = NULL;//crazy!! 

		cmd->type = get_cmd_type(xmlGetProp(cmd_list, "type"));

		if ((ptr = xmlGetProp(cmd_list, "file")) != 0)
			strcpy(cmd->file, ptr);

		if ((ptr = xmlGetProp(cmd_list, "address")) != 0)
			strcpy(cmd->address, ptr);

		cmd->perform = get_cmd_handler(cmd->type);
		cmd->file_size = get_file_size(cmd->file);
		strcpy(cmd->message, xmlNodeGetContent(cmd_list));
		cmd_list = cmd_list->next;

		return cmd;
	}

	return cmd;
}
Exemplo n.º 23
0
/* Takes a um executable file, loads the program and runs each instuction
 * in segment 0 until a halt is reached. 
 */
void UM_run(T um, const char *input)
{
        WORD_SIZE curr_inst;
        int size = get_file_size(input);

        assert(Segment_map(um->memory, size) == 0);

        load_file(um, size, input);

        while (true) {
                curr_inst = *prog_copy;
                route_instruct(um, curr_inst);
                prog_copy += 1;
                curr_inst = *prog_copy;
                route_instruct(um, curr_inst);
                prog_copy += 1;
                curr_inst = *prog_copy;
                route_instruct(um, curr_inst);
                prog_copy += 1;
        }
        return;
}
Exemplo n.º 24
0
void Verifier::recv_file(const char *file_name) {
  int size = 0;
  double time = 0;

#ifdef INTERFACE_MPI
  snprintf(full_file_name, BUFLEN - 1, "%s/%s", FOLDER_STATE, file_name);
  if (!FOLDER_STATE_SHARED) {
    Measurement get_time;
    MPI_Send(const_cast<char *>(file_name), strlen(file_name)+1, MPI_CHAR, 1,
             MPI_FILE_RECV, MPI_COMM_WORLD);

    MPI_Status stat;
    MPI_Probe(MPI_COORD_RANK, MPI_FILE_RECV, MPI_COMM_WORLD, &stat);
    MPI_Get_count(&stat, MPI_BYTE, &size);
    char *buf = new char[size];
    get_time.begin_with_init();
    MPI_Recv(buf, size, MPI_BYTE, MPI_COORD_RANK, MPI_FILE_RECV,
             MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    get_time.end();
    FILE *fp = fopen(full_file_name, "w");
    fwrite(buf, size, 1, fp);
    fclose(fp);
    time = get_time.get_papi_elapsed_time();
    delete[] buf;
  }
#else
  snprintf(full_file_name, BUFLEN - 1, "%s/%s", FOLDER_STATE, file_name);
  snprintf(download_url, BUFLEN - 1, "%s?file=%s", prover_download_url,
           file_name);
  curl->recv_file(full_file_name, download_url, &size, &time);

#endif

  size = get_file_size(full_file_name);
  network_bytes_rcvd += size;
  network_rcv_time_elapsed += time;
  if (strstr(file_name, OUTPUT_FILE_NAME_SUBSTR) != NULL)
    network_bytes_output_rcvd += size;
}
Exemplo n.º 25
0
	T* SequenceReader<T>::read(int& size) {
		size = get_file_size();

		if((size) <= 0) {
			fprintf(stderr, "Erro de leitura sequence_size <= 0\n");
			return NULL;
		}

		T* result = NULL;

		try {
			result = new T[size + 1];
		} catch(std::exception& e) {
			fprintf(stderr, "Erro ao alocar memoria para a sequencia %s\n", e.what());
			return NULL;
		}

		fread(result, sizeof(T), size, f);

		result[size] = 0;
		return result;
	}
Exemplo n.º 26
0
/**
 * Allocate memory and load a file there
 * @param filename the file which should be loaded
 * @param fsize pointer on the size of file which will be loaded
 * @return file data buffer pointer
 */
char *
load_absolute_file (const char *const filename, Uint32 * const filesize)
{
  size_t fsize;
  FILE *fstream;
  char *buffer;
  fstream = fopen (filename, "r");
  if (fstream == NULL)
    {
      LOG_ERR ("can't open file  %s (%s)", filename, strerror (errno));
      return NULL;
    }
  fsize = get_file_size (fstream);
  (*filesize) = fsize;
  if (fsize == 0)
    {
      fclose (fstream);
      LOG_ERR ("file %s is empty!", filename);
      return NULL;
    }
  buffer = memory_allocation (fsize);
  if (buffer == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes!",
               filename, (Sint32) fsize);
      fclose (fstream);
      return NULL;
    }
  if (fread (buffer, sizeof (char), fsize, fstream) != fsize)
    {
      free_memory (buffer);
      LOG_ERR ("can't read file \"%s\" (%s)", filename, strerror (errno));
      fclose (fstream);
      return NULL;
    }
  fclose (fstream);
  LOG_DBG ("file \"%s\" was loaded in memory", filename);
  return buffer;
}
Exemplo n.º 27
0
                void set(uint64_t id, TValue value) {
                    if (id >= m_size) {
                        uint64_t new_size = id + size_increment;

                        // if the file backing this mmap is smaller than needed, increase its size
                        if (get_file_size() < sizeof(TValue) * new_size) {
                            if (ftruncate(m_fd, sizeof(TValue) * new_size) < 0) {
                                throw std::bad_alloc();
                            }
                        }

                        if (munmap(m_items, sizeof(TValue) * m_size) < 0) {
                            throw std::bad_alloc();
                        }
                        m_items = static_cast<TValue*>(mmap(NULL, sizeof(TValue) * new_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd, 0));
                        if (m_items == MAP_FAILED) {
                            throw std::bad_alloc();
                        }
                        m_size = new_size;
                    }
                    m_items[id] = value;
                }
Exemplo n.º 28
0
int32_t map_file_in(int32_t fd, char **buf, uint64_t *size, int32_t perm)
{
    int32_t rtrn = 0;

    /* Get the file's size. */
    rtrn = get_file_size(fd, size);
    if(rtrn < 0)
    {
        output->write(ERROR, "Can't get file size\n");
        return (-1);
    }

    /* Use MAP_SHARED otherwise the file won't change when we write it to disk. */
    (*buf) = mmap(0, (unsigned long)(*size), perm, MAP_SHARED, fd, 0);
    if((*buf) == MAP_FAILED)
    {
        output->write(ERROR, "mmap: %s\n", strerror(errno));
        return (-1);
    }

    return (0);
}
Exemplo n.º 29
0
int send_file(int work_sockfd, int sockfd, char* fileName) {
	char buffer[8192];
	FILE *fp;
	int len;
	
	bzero(buffer, 8192);
	if ((fp = fopen(fileName, "rb")) == NULL) {
		printf("fopen() error!\n");
		close(sockfd);
		return 1;
	}
	
	char *tmp_str = waiting_for(work_sockfd, "");
	char num[16];
	strcpy(num, split(tmp_str, " ", 2)[0]);
	if (strcmp(num, "150") != 0) {
		fclose(fp);
		close(sockfd);
		return 1;
	}
	sprintf(tmp_str, "(%d bytes).\r\n", get_file_size(fileName));
	printf("%s", tmp_str);
	
	len = 0;
	while((len = fread(buffer, 1, 8192, fp)) > 0) {
		int send_len;
		if ((send_len = send(sockfd, buffer, len, 0)) < 0) {
			printf("Error send(): %s(%d)\n", strerror(errno), errno);
		}
		bzero(buffer, 8192);
	}
	
	fclose(fp);
	close(sockfd);
	
	waiting_for(work_sockfd, "");
	
	return STATUS_OK;
}
Exemplo n.º 30
0
void *
ia_acc_open_firmware(const char *fw_path, unsigned *size)
{
    FILE *file;
    unsigned len;
    void *fw;

    if (!fw_path)
        return NULL;

    file = fopen(fw_path, "rb");
    if (!file)
        return NULL;

    len = get_file_size(file);

    if (!len) {
        fclose(file);
        return NULL;
    }

    fw = malloc(len);
    if (!fw) {
        fclose(file);
        return NULL;
    }

    if (fread(fw, 1, len, file) != len) {
        fclose(file);
        free(fw);
        return NULL;
    }

    *size = len;

    fclose(file);

    return fw;
}