Exemple #1
0
Fichier : fs.c Projet : darfux/jos
//=w=
//*lab5 ex6 challenge*
//modified for lab5 ex6 4MB challenge
//make the indirect blocks to be a link list
//so that we can expand the filebno space
int
file_block_walk(struct File *f, uint32_t filebno, uint32_t **ppdiskbno, bool alloc)
{
	int r;
	uint32_t *ptr;
	char *blk=NULL;
	
	int totalBlockNum = super->s_nblocks;
	int maxIndirect = DIV_ROUNDUP((totalBlockNum-NDIRECT), (INDRECTMOUNT+1));

	if(filebno < NDIRECT)
	{
		ptr = &f->f_direct[filebno];
	}
	else if(filebno < (NINDIRECT-NDIRECT)*maxIndirect+NDIRECT)
	{
		int fileIndNo = DIV_ROUNDUP(filebno-NDIRECT+1, INDRECTMOUNT);
		uint32_t* indirect = &(f->f_indirect);
		uint32_t* parentblk=NULL;
		int parentblkno=-1;
		//loop to find the owner of filebno
		for(; fileIndNo>0; fileIndNo--)
		{
			if ((*indirect) == 0)
			{
				if (alloc == 0) return -E_NOT_FOUND;
				if ((r = alloc_block()) < 0) return r;
				(*indirect) = r;
				if( indirect != &(f->f_indirect))
				{
					//if it's indirect block, 
					//refresh the next indirect block entry
					write_block(r);
				}
			}
			else
			{
				alloc = 0;	// we did not allocate a block
			}
			parentblk = (uint32_t*)blk;
			if ((r = read_block((*indirect), &blk)) < 0)
			{
				return r;
			}
			assert(blk != 0);
			if (alloc)		// must clear any block we allocated
			{
				memset(blk, 0, BLKSIZE);
			}
			//set the pointer to the next indirect block
			((uint32_t*)blk)[1] = parentblkno;
			parentblkno = (*indirect);
			indirect = (uint32_t*)blk;
		}
		ptr = (uint32_t*)blk + FILE_IND_BLKOFFSET(filebno);
	}
	else
	{
		return -E_INVAL;
	}

	*ppdiskbno = ptr;
	return 0;
}
Exemple #2
0
int main(int argc, char ** argv)
{
  if (stdout_is_piped()) // other wise you don't see the seg fault
    setup_segfault_handling(argv);
  
  assert_stdin_is_piped();
  assert_stdout_is_piped();
  //assert_stdin_or_out_is_piped();
  
  static char remove_columns_all[1000] = "";
  static char int_columns_all[1000] = "";
  static char intfromtime_columns_all[1000] = "";
  static char float_columns_all[1000] = "";
  static int output_header = 1;
  static int debug = 0;
  
  int c;
  while (1)
  {
    static struct option long_options[] = {
      {"remove", required_argument, 0, 'r'},
      {"makeint", required_argument, 0, 'i'},
      {"makeintfromtime", required_argument, 0, 't'},
      {"makefloat", required_argument, 0, 'f'},
      //{"add", no_argument, &output_header, 1},
      {"debug", no_argument, &debug, 1},
      {0, 0, 0, 0}
    };
    
    int option_index = 0;
    c = getopt_long(argc, argv, "r:i:", long_options, &option_index);
    if (c == -1) break;
    
    switch (c)
    {
      case 0: break;
      case 'r': strncpy(remove_columns_all, optarg, sizeof(remove_columns_all)); break;
      case 'i': strncpy(int_columns_all, optarg, sizeof(int_columns_all)); break;
      case 't': strncpy(intfromtime_columns_all, optarg, sizeof(intfromtime_columns_all)); break;
      case 'f': strncpy(float_columns_all, optarg, sizeof(float_columns_all)); break;
      default: abort();
    }
  }
  
  char remove_columns_copy[1000] = "";
  strncpy(remove_columns_copy, remove_columns_all, 1000);
  
  char int_columns_copy[1000] = "";
  strncpy(int_columns_copy, int_columns_all, 1000);

  char intfromtime_columns_copy[1000] = "";
  strncpy(intfromtime_columns_copy, intfromtime_columns_all, 1000);

  char float_columns_copy[1000] = "";
  strncpy(float_columns_copy, float_columns_all, 1000);
  
  int num_remove_columns = 0;
  char ** remove_columns = NULL;
  char * pch = strtok(remove_columns_all, ",");
  while (pch != NULL)
  {
    num_remove_columns++;
    remove_columns = realloc(remove_columns, sizeof(char*)*num_remove_columns);
    remove_columns[num_remove_columns-1] = pch;
    pch = strtok(NULL, ",");
  }
  
  int num_int_columns = 0;
  char ** int_columns = NULL;
  pch = strtok(int_columns_all, ",");
  while (pch != NULL)
  {
    num_int_columns++;
    int_columns = realloc(int_columns, sizeof(char*)*num_int_columns);
    int_columns[num_int_columns-1] = pch;
    pch = strtok(NULL, ",");
  }
  
  int num_intfromtime_columns = 0;
  char ** intfromtime_columns = NULL;
  pch = strtok(intfromtime_columns_all, ",");
  while (pch != NULL)
  {
    num_intfromtime_columns++;
    intfromtime_columns = realloc(intfromtime_columns, sizeof(char*)*num_intfromtime_columns);
    intfromtime_columns[num_intfromtime_columns-1] = pch;
    pch = strtok(NULL, ",");
  }
  
  int num_float_columns = 0;
  char ** float_columns = NULL;
  pch = strtok(float_columns_all, ",");
  while (pch != NULL)
  {
    num_float_columns++;
    float_columns = realloc(float_columns, sizeof(char*)*num_float_columns);
    float_columns[num_float_columns-1] = pch;
    pch = strtok(NULL, ",");
  }
  
  int i,j;
  struct Block * block = NULL;
  while ((block = read_block(stdin)))
  {
    struct Block * newblock = new_block();
    newblock = copy_all_attributes(newblock, block);
    
    if (remove_columns_copy[0] != 0)
      newblock = add_string_attribute(newblock, "remove attributes", remove_columns_copy);
    
    if (int_columns_copy[0] != 0)
      newblock = add_string_attribute(newblock, "convert columns to int", int_columns_copy);
    
    if (intfromtime_columns_copy[0] != 0)
      newblock = add_string_attribute(newblock, "convert columns to time", intfromtime_columns_copy);
    
    if (float_columns_copy[0] != 0)
      newblock = add_string_attribute(newblock, "convert columns to float", float_columns_copy);
    
    int num_remove_column_ids = 0;
    int * remove_column_ids = NULL;
    
    for (i = 0 ; i < block->num_columns ; i++)
    {
      struct Column * col = get_column(block, i);
      for (j = 0 ; j < num_remove_columns ; j++)
      {
        // fprintf(stderr, "%s(%d(%d)) vs %s(%d) = %d\n", 
        //                  column_get_name(col), col->name_length, strlen(column_get_name(col)), 
        //                  remove_columns[j], strlen(remove_columns[j]), 
        //                   strcmp(column_get_name(col), remove_columns[j]));
        if (strcmp(column_get_name(col), remove_columns[j])==0) break;
      }
      if (j == num_remove_columns) // not a column to be removed
      {
        //fprintf(stderr, "%d: %s (%d) - do not remove\n", i, column_get_name(col), strlen(column_get_name(col)));
        for (j = 0 ; j < num_int_columns ; j++)
          if (strcmp(column_get_name(col), int_columns[j])==0) break;
        int l = 0;
        for (l = 0 ; l < num_intfromtime_columns ; l++)
          if (strcmp(column_get_name(col), intfromtime_columns[l])==0) break;
        int k = 0;
        for (k = 0 ; k < num_float_columns ; k++)
          if (strcmp(column_get_name(col), float_columns[k])==0) break;

        if (j == num_int_columns && k == num_float_columns && l == num_intfromtime_columns)
        {
          num_remove_column_ids++;
          remove_column_ids = realloc(remove_column_ids, sizeof(int)*num_remove_column_ids);
          remove_column_ids[num_remove_column_ids-1] = i;
          newblock = _add_column(newblock, col->type, col->bsize, column_get_name(col));
        }
      }
    }
    
    int num_int_column_ids = 0;
    int * int_column_ids = NULL;
    
    for (i = 0 ; i < block->num_columns ; i++)
    {
      struct Column * col = get_column(block, i);
      for (j = 0 ; j < num_int_columns ; j++)
        if (strcmp(column_get_name(col), int_columns[j])==0) break;
      if (j != num_int_columns)
      {
        num_int_column_ids++;
        int_column_ids = realloc(int_column_ids, sizeof(int)*num_int_column_ids);
        int_column_ids[num_int_column_ids-1] = i;
        newblock = add_int32_column(newblock, column_get_name(col));
      }
    }
    
    int num_intfromtime_column_ids = 0;
    int * intfromtime_column_ids = NULL;
    
    for (i = 0 ; i < block->num_columns ; i++)
    {
      struct Column * col = get_column(block, i);
      for (j = 0 ; j < num_intfromtime_columns ; j++)
        if (strcmp(column_get_name(col), intfromtime_columns[j])==0) break;
      if (j != num_intfromtime_columns)
      {
        num_intfromtime_column_ids++;
        intfromtime_column_ids = realloc(intfromtime_column_ids, sizeof(int)*num_intfromtime_column_ids);
        intfromtime_column_ids[num_intfromtime_column_ids-1] = i;
        newblock = add_int32_column(newblock, column_get_name(col));
      }
    }
    
    int num_float_column_ids = 0;
    int * float_column_ids = NULL;
    
    for (i = 0 ; i < block->num_columns ; i++)
    {
      struct Column * col = get_column(block, i);
      for (j = 0 ; j < num_float_columns ; j++)
        if (strcmp(column_get_name(col), float_columns[j])==0) break;
      if (j != num_float_columns)
      {
        num_float_column_ids++;
        float_column_ids = realloc(float_column_ids, sizeof(int)*num_float_column_ids);
        float_column_ids[num_float_column_ids-1] = i;
        newblock = add_double_column(newblock, column_get_name(col));
      }
    }
    
    newblock = set_num_rows(newblock, block->num_rows);
    
    for (i = 0 ; i < newblock->num_rows ; i++)
    {
      for (j = 0 ; j < num_remove_column_ids ; j++)
      {
        void * dst = get_cell(newblock, i, j);
        void * src = get_cell(block, i, remove_column_ids[j]);
        struct Column * col = get_column(block, remove_column_ids[j]);
        
        memcpy(dst, src, col->bsize);
      }
      for (j = 0 ; j < num_int_column_ids ; j++)
      {
        set_cell_from_int32(newblock, i, j + num_remove_column_ids, get_cell_as_int32(block, i, int_column_ids[j]));
      }
      for (j = 0 ; j < num_intfromtime_column_ids ; j++)
      {
        char * cell = get_cell(block, i, intfromtime_column_ids[j]);
        int len = strlen(cell);
        if (len >= 7)
        { 
          int32_t t = atoi(&cell[len-2]) + atoi(&cell[len-5])*60 + atoi(cell)*60*60;
          set_cell_from_int32(newblock, i, j + num_remove_column_ids + num_int_column_ids, t);
        }
        else
        {
          fprintf(stderr, "ABORTING: %s expecting time to be in #:##:## format. But length invalid. (%d)\n", __func__, len);
          exit(1);
        }
      }
      for (j = 0 ; j < num_float_column_ids ; j++)
      {
        set_cell_from_double(newblock, i, j + num_remove_column_ids + num_int_column_ids + num_intfromtime_column_ids, get_cell_as_double(block, i, float_column_ids[j]));
      }
    }
    free(remove_column_ids);
    free(int_column_ids);
    free(float_column_ids);
    
    write_block(stdout, newblock);
    free_block(newblock);
    free_block(block);
  }
}
Exemple #3
0
static void
flush_cache_block(struct sfs_fs *sfs, struct cache_block *cb) {
    write_block(sfs, cb->cache, SFS_BLKSIZE, cb->ino);
}
 /**
   * Saves the current chunk of vertex values
   */
 virtual void save(bool async=false) {
     for(int i=0; i <  (int)loadedblocks.size(); i++) {
         write_block(loadedblocks[i]);
     }
 }
void test_my_read() {
  // Create file /foo2/read-test.txt
	int fd = my_creat("/foo2/read-test.txt");
	
	int block_num = open_files[fd];
	
	printf("\ntest_my_read: file created at block %i\n", block_num);
	
	// Buffer to store data to write to file
	char buffer[BLOCKSIZE];
	char *buffer_ptr = buffer;
	
	int next_block = requestNextFreeBlock();
  setBlockInBitmapToStatus(1, next_block);

	printf("test_my_read: file 2nd block created at block %i\n", next_block);
	
	// Write first block of file
	short bytes_allocated = HEADER_SIZE + 20;
	*buffer_ptr = 'f';
  memcpy(++buffer_ptr, &next_block, BYTES_IN_INT);
	buffer_ptr += BYTES_IN_INT;
	memcpy(buffer_ptr, &bytes_allocated, BYTES_IN_SHORT);
	buffer_ptr += BYTES_IN_SHORT;
	char data[] = "1234567890abcdefghij";
	buffer_ptr = buffer;
	buffer_ptr += HEADER_SIZE;
	memcpy(buffer_ptr, data, 20);
	write_block(block_num, buffer);
	
	// Write second (last) block of file
	block_num = next_block;
	next_block = ROOT_BLOCK;
	bytes_allocated = HEADER_SIZE + 10;
	
	memset(buffer, 0, BLOCKSIZE);
	buffer_ptr = buffer;
	*buffer_ptr = 'f';
  memcpy(++buffer_ptr, &next_block, BYTES_IN_INT);
	buffer_ptr += BYTES_IN_INT;
	memcpy(buffer_ptr, &bytes_allocated, BYTES_IN_SHORT);
	buffer_ptr += BYTES_IN_SHORT;
	char data2[] = "ABCDEFGHIJ";
	buffer_ptr = buffer;
	buffer_ptr += HEADER_SIZE;
	memcpy(buffer_ptr, data2, 10);
	write_block(block_num, buffer);
	
	char buf[BLOCKSIZE * 4];
	memset(buf, 0, BLOCKSIZE * 4);
	my_close(fd);
	
	// This should produce an error
	printf("my_test_read: should produce error below.\n");
	int result = my_read(fd, buf, 25);
	
	if (result != -1) {
		printf("my_test_read: FAILED (should not read closed file).\n");
	}
	
	fd = my_open("/foo2/read-test.txt");
	int num_bytes_requested = 23;
	result = my_read(fd, buf, num_bytes_requested);
	buf[num_bytes_requested] = '\0';
	
	if (strcmp(buf, "1234567890abcdefghijABC") == 0) {
	  printf("my_test_read: PASSED 1. %i bytes read.  Data read: %s\n", result, buf);
  }
  else {
		printf("my_test_read: FAILED 1.\n");
  }

	num_bytes_requested = 5;
	result = my_read(fd, buf, num_bytes_requested);
	buf[num_bytes_requested] = '\0';
	if (strcmp(buf, "DEFGH") == 0) {
	  printf("my_test_read: PASSED 2. %i bytes read.  Data read: %s\n", result, buf);
  }
  else {
		printf("my_test_read: FAILED 2.\n");
  }	
	my_close(fd);
	
	fd = my_open("/foo2/read-test.txt");
	num_bytes_requested = 2;
	result = my_read(fd, buf, num_bytes_requested);
	buf[num_bytes_requested] = '\0';
	
	if (strcmp(buf, "12") == 0) {
	  printf("my_test_read: PASSED 3. %i bytes read.  Data read: %s\n", result, buf);
  }
  else {
		printf("my_test_read: FAILED 3.\n");
  }

	num_bytes_requested = 20;
	result = my_read(fd, buf, num_bytes_requested);
	buf[num_bytes_requested] = '\0';
	
	if (strcmp(buf, "34567890abcdefghijAB") == 0) {
	  printf("my_test_read: PASSED 4. %i bytes read.  Data read: %s\n", result, buf);
  }
  else {
		printf("my_test_read: FAILED 4.\n");
  }

	num_bytes_requested = 20;
	result = my_read(fd, buf, num_bytes_requested);
	buf[result] = '\0';
	
	if (strcmp(buf, "CDEFGHIJ") == 0) {
	  printf("my_test_read: PASSED 5. %i bytes read.  Data read: %s\n", result, buf);
  }
  else {
		printf("my_test_read: FAILED 5.\n");
  }
}
Exemple #6
0
int main(int argc, char ** argv)
{
  if (stdout_is_piped()) // other wise you don't see the seg fault
    setup_segfault_handling(argv);
  
  assert_stdin_is_piped();
  assert_stdout_is_piped();
  //assert_stdin_or_out_is_piped();
  
  static char remove_attributes_all[1000] = "";
  static char int_attributes_all[1000] = "";
  static int debug = 0;
  
	struct Params * params = NULL;
	params = add_string_param(params, "remove", 'r', remove_attributes_all, 0);
	params = add_string_param(params, "makeint", 'i', int_attributes_all, 0);
	params = add_flag_param(params, "debug", 'd', &debug, 0);
	
  char remove_attributes_copy[1000] = "";
  strncpy(remove_attributes_copy, remove_attributes_all, 1000);
  
  char int_attributes_copy[1000] = "";
  strncpy(int_attributes_copy, int_attributes_all, 1000);
  
  int num_remove_attributes = 0;
  char ** remove_attributes = NULL;
  char * pch = strtok(remove_attributes_all, ",");
  while (pch != NULL)
  {
    num_remove_attributes++;
    remove_attributes = realloc(remove_attributes, sizeof(char*)*num_remove_attributes);
    remove_attributes[num_remove_attributes-1] = pch;
    pch = strtok(NULL, ",");
  }
  
  int num_int_attributes = 0;
  char ** int_attributes = NULL;
  pch = strtok(int_attributes_all, ",");
  while (pch != NULL)
  {
    num_int_attributes++;
    int_attributes = realloc(int_attributes, sizeof(char*)*num_int_attributes);
    int_attributes[num_int_attributes-1] = pch;
    pch = strtok(NULL, ",");
  }
  
  int i,j;
  struct Block * block = NULL;
  while ((block = read_block(stdin)))
  {
    struct Block * newblock = new_block();
    newblock = copy_all_attributes(newblock, block);
    
    if (remove_attributes_copy[0] != 0)
      newblock = add_string_attribute(newblock, "remove attributes", remove_attributes_copy);
    
    if (int_attributes_copy[0] != 0)
      newblock = add_string_attribute(newblock, "convert attributes to int", int_attributes_copy);
    
    int num_remove_attribute_ids = 0;
    int * remove_attribute_ids = NULL;
    
    for (i = 0 ; i < block->num_attributes ; i++)
    {
      struct Attribute * attr = get_attribute(block, i);
      for (j = 0 ; j < num_remove_attributes ; j++)
      {
        // fprintf(stderr, "%s(%d(%d)) vs %s(%d) = %d\n", 
        //                  attribute_get_name(attr), attr->name_length, strlen(attribute_get_name(attr)), 
        //                  remove_attributes[j], strlen(remove_attributes[j]), 
        //                   strcmp(attribute_get_name(attr), remove_attributes[j]));
        if (strcmp(attribute_get_name(attr), remove_attributes[j])==0) break;
      }
      if (j == num_remove_attributes) // not a attribute to be removed
      {
        //fprintf(stderr, "%d: %s (%d) - do not remove\n", i, attribute_get_name(attr), strlen(attribute_get_name(attr)));
        for (j = 0 ; j < num_int_attributes ; j++)
          if (strcmp(attribute_get_name(attr), int_attributes[j])==0) break;
        if (j == num_int_attributes)
        {
          num_remove_attribute_ids++;
          remove_attribute_ids = realloc(remove_attribute_ids, sizeof(int)*num_remove_attribute_ids);
          remove_attribute_ids[num_remove_attribute_ids-1] = i;
          newblock = _add_attribute(newblock, attr->type, attr->value_length, attribute_get_name(attr), attribute_get_value(attr));
        }
      }
    }
    
    int num_int_attribute_ids = 0;
    int * int_attribute_ids = NULL;
    
    for (i = 0 ; i < block->num_attributes ; i++)
    {
      struct Attribute * attr = get_attribute(block, i);
      for (j = 0 ; j < num_int_attributes ; j++)
        if (strcmp(attribute_get_name(attr), int_attributes[j])==0) break;
      if (j != num_int_attributes)
      {
        num_int_attribute_ids++;
        int_attribute_ids = realloc(int_attribute_ids, sizeof(int)*num_int_attribute_ids);
        int_attribute_ids[num_int_attribute_ids-1] = i;
        newblock = add_int32_attribute(newblock, attribute_get_name(attr), *(int32_t*)attribute_get_value(attr));
      }
    }
    
    newblock = set_num_rows(newblock, block->num_rows);
    
    for (i = 0 ; i < newblock->num_rows ; i++)
    {
      for (j = 0 ; j < num_remove_attribute_ids ; j++)
      {
        void * dst = get_cell(newblock, i, j);
        void * src = get_cell(block, i, remove_attribute_ids[j]);
        struct Attribute * attr = get_attribute(block, remove_attribute_ids[j]);
        
        memcpy(dst, src, attr->value_length);
      }
      for (j = 0 ; j < num_int_attribute_ids ; j++)
      {
        set_cell_from_int32(newblock, i, j + num_remove_attribute_ids, get_cell_as_int32(block, i, int_attribute_ids[j]));
      }
    }
    free(remove_attribute_ids);
    free(int_attribute_ids);
    
    write_block(stdout, newblock);
    free_block(newblock);
    free_block(block);
  }
}
Exemple #7
0
/***********************************************************************
 *            WriteConsoleW   (KERNEL32.@)
 */
BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
			  LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
{
    DWORD			mode;
    DWORD			nw = 0;
    WCHAR*			psz = (WCHAR*)lpBuffer;
    CONSOLE_SCREEN_BUFFER_INFO	csbi;
    int				k, first = 0;

    TRACE("%d %s %ld %p %p\n",
	  hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
	  nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);

    if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;

    if (!GetConsoleMode(hConsoleOutput, &mode) ||
	!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
	return FALSE;

    if (mode & ENABLE_PROCESSED_OUTPUT)
    {
	int	i;

	for (i = 0; i < nNumberOfCharsToWrite; i++)
	{
	    switch (psz[i])
	    {
	    case '\b': case '\t': case '\n': case '\a': case '\r':
		/* don't handle here the i-th char... done below */
		if ((k = i - first) > 0)
		{
		    if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
			goto the_end;
		    nw += k;
		}
		first = i + 1;
		nw++;
	    }
	    switch (psz[i])
	    {
	    case '\b':
		if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
		break;
	    case '\t':
	        {
		    WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};

		    if (!write_block(hConsoleOutput, &csbi, mode, tmp,
				     ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
			goto the_end;
		}
		break;
	    case '\n':
		next_line(hConsoleOutput, &csbi);
		break;
 	    case '\a':
		Beep(400, 300);
 		break;
	    case '\r':
		csbi.dwCursorPosition.X = 0;
		break;
	    default:
		break;
	    }
	}
    }

    /* write the remaining block (if any) if processed output is enabled, or the
     * entire buffer otherwise
     */
    if ((k = nNumberOfCharsToWrite - first) > 0)
    {
	if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
	    goto the_end;
	nw += k;
    }

 the_end:
    SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
    if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
    return nw != 0;
}
Exemple #8
0
/*
 * tentec_set_mode
 * Assumes rig!=NULL
 */
int tentec_set_mode(RIG *rig, vfo_t vfo, rmode_t mode, pbwidth_t width)
{
	struct tentec_priv_data *priv = (struct tentec_priv_data *)rig->state.priv;
	struct rig_state *rs = &rig->state;
	char ttmode;
	rmode_t saved_mode;
	pbwidth_t saved_width;
	int mdbuf_len, ttfilter, retval;
	char mdbuf[32];

	switch (mode) {
		case RIG_MODE_USB:      ttmode = TT_USB; break;
		case RIG_MODE_LSB:      ttmode = TT_LSB; break;
		case RIG_MODE_CW:       ttmode = TT_CW; break;
		case RIG_MODE_AM:       ttmode = TT_AM; break;
		case RIG_MODE_FM:       ttmode = TT_FM; break;
		default:
			rig_debug(RIG_DEBUG_ERR,
							"tentec_set_mode: unsupported mode %d\n",
							mode);
			return -RIG_EINVAL;
	}

		/* backup current values
		 * in case we fail to write to port
		 */
	saved_mode = priv->mode;
	saved_width = priv->width;

	if (width != RIG_PASSBAND_NOCHANGE) {
		if (width == RIG_PASSBAND_NORMAL)
			width = rig_passband_normal(rig, mode);

		for (ttfilter=0; tentec_filters[ttfilter] != 0; ttfilter++) {
			if (tentec_filters[ttfilter] == width)
				break;
		}
		if (tentec_filters[ttfilter] != width) {
			rig_debug(RIG_DEBUG_ERR,
								"tentec_set_mode: unsupported width %d\n",
								width);
			return -RIG_EINVAL;
		}
		priv->width = width;
	}
	
	priv->mode = mode;

	tentec_tuning_factor_calc(rig);

	if (width != RIG_PASSBAND_NOCHANGE) {
		mdbuf_len = sprintf(mdbuf,  "W%c" EOM
												"N%c%c%c%c%c%c" EOM
												"M%c" EOM,
												ttfilter,
												priv->ctf >> 8, priv->ctf & 0xff,
												priv->ftf >> 8, priv->ftf & 0xff,
												priv->btf >> 8, priv->btf & 0xff,
												ttmode);
		retval = write_block(&rs->rigport, mdbuf, mdbuf_len);
		if (retval != RIG_OK) {
			priv->mode = saved_mode;
			priv->width = saved_width;
			return retval;
		}
	}
Exemple #9
0
void * test_main(void *val) 
{
    int id;
    int s_fd;
    int w_fd;
    int data_len;
    int num;
    int endf;
    int ends;
    char path[MAX_BUF_SIZE] = "./r_test";
    char data_buf[MAX_BUF_SIZE] = {0};

    int sockfd = 0;
    
    id = (int)getpid();

    printf("thread with id %d start \n", id);
    sprintf(path + strlen(path), "%d", id);
    w_fd = open(path, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);

    if (w_fd < 0)
    {
        printf("open file %s failed\n", path);
        exit(0);
    }

    sockfd = tcp_server_creat("127.0.0.1", 11111);
    if (sockfd < 0)
    {
        printf("tcp create server failed\n");
        return NULL;
    }

    s_fd = open("s_test", O_RDONLY, S_IRWXU);
    if (s_fd < 0)
    {
        printf("id %d open file s_test failed\n", id);
        return NULL;
    }

    while(1)
    {
            bzero(data_buf, MAX_BUF_SIZE);

            num = read_block(s_fd, data_buf, MAX_BUF_SIZE/4, &endf);
            data_len = num;

            num = write_block(sockfd, data_buf, data_len);
            data_len = num;

            num = read_block(sockfd, data_buf, data_len, &ends);
            
            write_block(w_fd, data_buf, num);

            if(endf){
                close(s_fd);
                close(w_fd);
                close(sockfd);
                return NULL;
            }
    } 
}
Exemple #10
0
int main(int argc, char ** argv)
{
  if (stdout_is_piped()) // other wise you don't see the seg fault
    setup_segfault_handling(argv);
  
  assert_stdin_is_piped();
  assert_stdout_is_piped();
  //assert_stdin_or_out_is_piped();
  
  static char column_name[1000] = "";
  static int sort_that_column = 0;
  static int debug = 0;
  static int reverse = 0;
  
  int c;
  while (1)
  {
    static struct option long_options[] = {
      {"column", required_argument, 0, 'c'},
      {"sort", no_argument, 0, 's'},
      {"reverse", no_argument, 0, 'r'},
      {"debug", no_argument, &debug, 1},
      {0, 0, 0, 0}
    };
    
    int option_index = 0;
    c = getopt_long(argc, argv, "c:sr", long_options, &option_index);
    if (c == -1) break;
    
    switch (c)
    {
      case 0: break;
      case 'c': strncpy(column_name, optarg, sizeof(column_name)); break;
      case 's': sort_that_column = 1; break;
      case 'r': reverse = 1; break;
      default: abort();
    }
  }
  
  struct Block * block = NULL;
  while ((block = read_block(stdin)))
  {
    int column_id = get_column_id_by_name_or_exit(block, column_name);
    
    struct Column * column = get_column(block, column_id);
    
    struct Block * newblock = new_block();
    newblock = copy_all_attributes(newblock, block);
    newblock = copy_all_columns(newblock, block);
    
    newblock = add_command(newblock, argc, argv);
    
    int i;
    for (i = 0 ; i < block->num_rows ; i++)
    {
      void * cell = get_cell(block, i, column_id);
      
      int j;
      for (j = 0 ; j < newblock->num_rows ; j++)
      {
        if (memcmp(cell, get_cell(newblock, j, column_id), column->bsize)==0) 
        {
          // found
          break;
        }
      }
      
      if (j == newblock->num_rows) // not found
      {
        newblock = add_row(newblock);
        memcpy(get_row(newblock, newblock->num_rows-1), get_row(block, i), block->row_bsize);
      }
    }
    
    if (sort_that_column == 1 && column->type == TYPE_INT)
      newblock = sort_block_using_int32_column(newblock, column_id, reverse);
    
    write_block(stdout, newblock);
    free_block(newblock);
    free_block(block);
  }
}
int write_shm_queue(void* handle, const char* to_write_buf, int buf_len)
{
	
	int ret;
	shm_queue_handle_t *shmq_handle = (shm_queue_handle_t*)handle;
	
	if(NULL == shmq_handle)
	{
		return SHM_HANDLE_NULL;
	}
	
	if(shmq_handle->op_mode != OP_MODE_WRITE)
	{
		return SHM_OP_WRONG;
	}

	if(shmq_handle->pool_size < buf_len)
	{
		return SHM_BUF_SHORT;
	}
	
	pthread_rwlock_wrlock(&(shmq_handle->shm_que_info->rwlock));
	int f_ret;
	while((f_ret = is_full(shmq_handle->que,shmq_handle->para_queue_size)) > 0 
		|| shmq_handle->shm_que_info->pool_left_size < buf_len)
	{
		block_info_t *head_block;
		int head_offset = sizeof(shm_queue_info_t) + sizeof(circular_array_t) + sizeof(block_info_t) * (shmq_handle->que->head);
		head_block = (block_info_t*)((char*)(shmq_handle->shm_que_info) + head_offset);

		if(shmq_handle->who_prior == READ_PRIO)
		{
			int i = 0;
			for( i = 0; i < MAX_PROC_NUM; i++)
			{
				if(shmq_handle->shm_que_info->read_flags[i] == FLAG_TRUE)
				{
					while(head_block->flags[i] == FLAG_FALSE)
					{
						/*
							i think a clock will be here when i have more time
						*/
					}
				}
			}
		}

		else if(shmq_handle->who_prior == WRITE_PRIO)
		{
			int i = 0;
			for(i = 0; i < MAX_PROC_NUM; i++)
			{
				if(shmq_handle->shm_que_info->read_flags[i] == FLAG_TRUE && head_block->flags[i] == FLAG_FALSE)
				{
					shmq_handle->readers_miss[i].miss_bytes += head_block->block_size;
					shmq_handle->readers_miss[i].miss_block_num++;
				}				
			}			
		}		

		
		ret = out_queue(shmq_handle->que,shmq_handle->para_queue_size);
		if(ret == SHM_OK)
		{			
			shmq_handle->shm_que_info->pool_left_size +=  head_block->block_size;
		}
		
		else
		{
			pthread_rwlock_unlock(&(shmq_handle->shm_que_info->rwlock));
			return SHM_OUT_QUEUE_FAIL;
		}	
	}

	ret = is_full(shmq_handle->que,shmq_handle->para_queue_size);  
	
	if(ret < 0 && shmq_handle->shm_que_info->pool_left_size >= buf_len)
	{   
		write_block(shmq_handle,to_write_buf,buf_len);
	}      
	
	else
	{
		pthread_rwlock_unlock(&(shmq_handle->shm_que_info->rwlock));
		return SHM_NO_SPACE;
	}           
	
	pthread_rwlock_unlock(&(shmq_handle->shm_que_info->rwlock));
	return SHM_OK;
}
Exemple #12
0
int main(int argc, char **argv)
{
    char          *fname;
    unsigned char *buf;  // EBLOCKSIZE
    FILE          *infile;
    long          i;
    off_t         insize;
    int		  readlen;

    int		  skip;

    if (argc < 6) { 
        fprintf(stderr, "%s: zblocksize hashname signed_file_name spec_file_name zdata_file_name [ #blocks ]\n", argv[0]);
        return EXIT_FAILURE;
    }

    if (argc == 7)
        eblocks = strtol(argv[6], 0, 0);

    zblocksize = strtol(argv[1], 0, 0);

    buf = malloc(zblocksize);
    LTC_ARGCHK(buf != 0);

    /*
     * For zlib compress, the destination buffer needs to be 1.001 x the
     * src buffer size plus 12 bytes
     */
    zbufsize = ((zblocksize * 102) / 100) + 12;
    zbuf = malloc(zbufsize);
    LTC_ARGCHK(zbuf != 0);

    LTC_ARGCHK(register_hash(&sha256_desc) != -1);
    LTC_ARGCHK(register_hash(&rmd160_desc) != -1);
    LTC_ARGCHK(register_hash(&md5_desc) != -1);

    hashname = argv[2];
    hashid = find_hash(hashname);
    LTC_ARGCHK(hashid >= 0);

    /* open filesystem image file */
    infile = fopen(argv[3], "rb");
    LTC_ARGCHK(infile != NULL);

    /* open output file */
    outfile = fopen(argv[4], "wb");
    LTC_ARGCHK(outfile != NULL);

	LTC_ARGCHK(fputs("[ifndef] #eblocks-written\n", outfile) >= 0);
	LTC_ARGCHK(fputs("[ifdef] last-eblock#\n", outfile) >= 0);
	LTC_ARGCHK(fputs(": pdup  ( n -- n' )  dup  last-eblock# max  ;\n", outfile) >= 0);
	LTC_ARGCHK(fputs("also nand-commands  patch pdup dup zblock:  previous\n", outfile) >= 0);
	LTC_ARGCHK(fputs("[then]\n", outfile) >= 0);
	LTC_ARGCHK(fputs("[then]\n", outfile) >= 0);

    /* open zdata file */
    zfile = fopen(argv[5], "wb");
    LTC_ARGCHK(zfile != NULL);

    if (eblocks == -1) {
        (void)fseek(infile, 0L, SEEK_END);
        insize = ftello(infile);
        (void)fseek(infile, 0L, SEEK_SET);

        eblocks = (insize + zblocksize - 1) / zblocksize;
//    LTC_ARGCHK((eblocks * zblocksize) == insize);
    }

    eblocks = read_extents(infile) + 1;

    /* Remove possible path prefix */
    fname = strrchr(argv[5], '/');
    if (fname == NULL)
        fname = argv[5];
    else
        ++fname;

    fprintf(outfile, "data: %s\n", fname);
    fprintf(outfile, "zblocks: %lx %lx\n", zblocksize, eblocks);
    fprintf(zfile,   "zblocks: %lx %lx\n", zblocksize, eblocks);

    fprintf(stdout, "Total blocks: %ld\n", eblocks);

    /* wipe the partition table first in case of partial completion */
    memset(buf, 0, zblocksize);
    write_block(0, buf);

    /* make a hash of the file */
    for (i=1; i < eblocks; i++) {
        if (!eblocks_used[i])
            continue;

        fseeko(infile, (uint64_t) i * zblocksize, SEEK_SET);
        readlen = read_block(buf, infile, i == eblocks-1);
        LTC_ARGCHK(readlen == zblocksize);

        write_block(i, buf);
        fprintf(stdout, "\r%ld", i);  fflush(stdout);
    }

    fseek(infile, 0L, SEEK_SET);
    readlen = read_block(buf, infile, 0 == eblocks-1);
    LTC_ARGCHK(readlen == zblocksize);
    write_block(0, buf);

    fprintf(outfile, "zblocks-end:\n");
    fprintf(zfile,   "zblocks-end:\n");

    fclose(infile);
    fclose(outfile);

	putchar('\n');
    return EXIT_SUCCESS;
}
Exemple #13
0
int main(int argc, char ** argv)
{
	if (stdout_is_piped()) // other wise you don't see the seg fault
		setup_segfault_handling(argv);
	
	assert_stdin_is_piped();
	//assert_stdout_is_piped();
	//assert_stdin_or_out_is_piped();
	
	static char clamp_bbox_char[1000] = "";
	static int debug = 0;
	static double clamp_bbox[4] = {-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX};
	
	int c;
	while (1) {
		static struct option long_options[] = {
			{"bbox", required_argument, 0, 'b'},
			{"debug", no_argument, &debug, 1},
			{0, 0, 0, 0}
		};
		
		int option_index = 0;
		c = getopt_long(argc, argv, "b:", long_options, &option_index);
		if (c == -1) break;
		
		switch (c) {
			case 0: break;
			case 'b': strncpy(clamp_bbox_char, optarg, sizeof(clamp_bbox_char)); break;
			default: abort();
		}
	}
	
	if (clamp_bbox_char[0] != 0) {
		char * ptr = strtok(clamp_bbox_char, " ,");
		if (ptr == NULL) fprintf(stderr, "ERROR: Usage: %s --bbox=\"0,0,1,1\"	(min_x,max_x,min_y,max_y)", argv[0]);
		clamp_bbox[0] = atof(ptr);
		ptr = strtok(NULL, " ,");
		if (ptr == NULL) fprintf(stderr, "ERROR: Usage: %s --bbox=\"0,0,1,1\"	(min_x,min_y,max_x,max_y)", argv[0]);
		clamp_bbox[1] = atof(ptr);
		ptr = strtok(NULL, " ,");
		if (ptr == NULL) fprintf(stderr, "ERROR: Usage: %s --bbox=\"0,0,1,1\"	(min_x,min_y,max_x,max_y)", argv[0]);
		clamp_bbox[2] = atof(ptr);
		ptr = strtok(NULL, " ,");
		if (ptr == NULL) fprintf(stderr, "ERROR: Usage: %s --bbox=\"0,0,1,1\"	(min_x,min_y,max_x,max_y)", argv[0]);
		clamp_bbox[3] = atof(ptr);
		
		fprintf(stderr, "clamp x,y to: {%f,%f,%f,%f}\n", clamp_bbox[0], clamp_bbox[1], clamp_bbox[2], clamp_bbox[3]);
	}
	
	struct Block * block = NULL;
	while ((block = read_block(stdin))) {
		
		if (clamp_bbox_char[0] != 0) {
			block = add_command(block, argc, argv);
		}
		
		double bbox[2][2] = {{FLT_MAX, -FLT_MAX}, {FLT_MAX, -FLT_MAX}};
		
		int i;
		for (i = 0 ; i < block->num_rows ; i++) {
			double x = get_x(block, i);
			double y = get_y(block, i);
			
			if (x < bbox[0][0]) bbox[0][0] = x; if (x > bbox[0][1]) bbox[0][1] = x;
			if (y < bbox[1][0]) bbox[1][0] = y; if (y > bbox[1][1]) bbox[1][1] = y;
		}
		
		if (clamp_bbox_char[0] != 0) {
			double dx = clamp_bbox[0] - clamp_bbox[2];
			double dy = clamp_bbox[1] - clamp_bbox[3];
			for (i = 0 ; i < block->num_rows ; i++) {
				double x = get_x(block, i);
				double y = get_y(block, i);
				//fprintf(stderr, "%f inside %f,%f (%f), dx = %f\n", x, bbox[0][0], bbox[0][1], ((x-bbox[0][0])/(bbox[0][1]-bbox[0][0])), dx);
				//fprintf(stderr, "%f,%f\n", x, y);
				set_xy(block, i, ((x-bbox[0][0])/(bbox[0][1]-bbox[0][0]))*dx+clamp_bbox[0], ((y-bbox[1][0])/(bbox[1][1]-bbox[1][0]))*dy+clamp_bbox[1]);
				x = get_x(block, i);
				y = get_y(block, i);
				//fprintf(stderr, "becomes %f,%f\n", x, y);
			}
		} else {
		
			long * offsets = alloca(sizeof(long)*block->num_columns);
			memset(offsets, 0, sizeof(long)*block->num_columns);
			
			int i,j;
			for (i = 0 ; i < block->num_columns ; i++)
				offsets[i] = get_cell(block, 0, i) - get_row(block, 0);
			
			for (i = 0 ; i < block->num_columns ; i++)
			{
				struct Column * column = get_column(block, i);
				if (column->type == TYPE_INT && column->bsize == 4)
				{
					int min = *(int*)(get_row(block, 0)+offsets[i]);
					int max = min;
					for (j = 0 ; j < block->num_rows ; j++)
					{
						void * row = get_row(block, j);
						int value = *(int*)(row+offsets[i]);
						if (value > max) max = value;
						if (value < min) min = value;
					}
					fprintf(stderr, "%s: %d to %d\n", column_get_name(column), min, max);
				}
				else if (column->type == TYPE_INT && column->bsize == 8)
				{
					long min = *(long*)(get_row(block, 0)+offsets[i]);
					long max = min;
					for (j = 0 ; j < block->num_rows ; j++)
					{
						void * row = get_row(block, j);
						long value = *(long*)(row+offsets[i]);
						if (value > max) max = value;
						if (value < min) min = value;
					}
					fprintf(stderr, "%s: %ld to %ld\n", column_get_name(column), min, max);
				}
				else if (column->type == TYPE_FLOAT && column->bsize == 4)
				{
					float min = *(float*)(get_row(block, 0)+offsets[i]);
					float max = min;
					for (j = 0 ; j < block->num_rows ; j++)
					{
						void * row = get_row(block, j);
						float value = *(float*)(row+offsets[i]);
						if (value > max) max = value;
						if (value < min) min = value;
					}
					fprintf(stderr, "%s: %f to %f\n", column_get_name(column), min, max);
				}
				else if (column->type == TYPE_FLOAT && column->bsize == 8)
				{
					double min = *(double*)(get_row(block, 0)+offsets[i]);
					double max = min;
					for (j = 0 ; j < block->num_rows ; j++)
					{
						void * row = get_row(block, j);
						double value = *(double*)(row+offsets[i]);
						if (value > max) max = value;
						if (value < min) min = value;
					}
					fprintf(stderr, "%s: %lf to %lf\n", column_get_name(column), min, max);
				}
				else if (column->type == TYPE_CHAR)
				{
					int max = 0, count = 0;
					for (j = 0 ; j < block->num_rows ; j++)
					{
						void * row = get_row(block, j);
						int value = strlen((char*)(row+offsets[i]));
						if (value > max) { max = value; count = 1; }
						else if (value == max) count++;
					}
					fprintf(stderr, "%s: max strlen = %d (field size is %d), %d rows at that length\n", column_get_name(column), max, column->bsize, count);
				}
				else
					fprintf(stderr, "doesn't do %s %d\n", column_get_name(column), column->type);
			}
		}
		
		if (stdout_is_piped()) {
			write_block(stdout, block);
		}
		
		free_block(block);
	}
}
Exemple #14
0
int
Write_Disk(const struct disk *d1)
{
	struct sun_disklabel *sl;
	struct chunk *c, *c1, *c2;
	int i;
	char *p;
	u_long secpercyl;
	char device[64];
	u_char buf[SUN_SIZE];
	int fd;

	strcpy(device, _PATH_DEV);
	strcat(device, d1->name);

	fd = open(device, O_RDWR);
	if (fd < 0) {
		warn("open(%s) failed", device);
		return (1);
	}

	sl = calloc(sizeof *sl, 1);
	c = d1->chunks;
	c2 = c->part;
	secpercyl = d1->bios_sect * d1->bios_hd;
	sl->sl_pcylinders = c->size / secpercyl;
	sl->sl_ncylinders = c2->size / secpercyl;
	sl->sl_acylinders = sl->sl_pcylinders - sl->sl_ncylinders;
	sl->sl_magic = SUN_DKMAGIC;
	sl->sl_nsectors = d1->bios_sect;
	sl->sl_ntracks = d1->bios_hd;
	if (c->size > 4999 * 1024 * 2) {
		sprintf(sl->sl_text, "FreeBSD%luG cyl %u alt %u hd %u sec %u",
			(c->size + 1024 * 1024) / (2 * 1024 * 1024),
			sl->sl_ncylinders, sl->sl_acylinders,
			sl->sl_ntracks, sl->sl_nsectors);
	} else {
		sprintf(sl->sl_text, "FreeBSD%luM cyl %u alt %u hd %u sec %u",
			(c->size + 1024) / (2 * 1024),
			sl->sl_ncylinders, sl->sl_acylinders,
			sl->sl_ntracks, sl->sl_nsectors);
	}
	sl->sl_interleave = 1;
	sl->sl_sparespercyl = 0;
	sl->sl_rpm = 3600;

	for (c1 = c2->part; c1 != NULL; c1 = c1->next) {
		p = c1->name;
		p += strlen(p);
		p--;
		if (*p < 'a')
			continue;
		i = *p - 'a';
		if (i >= SUN_NPART)
			continue;
		sl->sl_part[i].sdkp_cyloffset = c1->offset / secpercyl;
		sl->sl_part[i].sdkp_nsectors = c1->size;
		for (i = 1; i < 16; i++) {
			write_block(fd, c1->offset + i, d1->boot1 + (i * 512),
			    512);
		}
	}

	/*
	 * We need to fill in the "RAW" partition as well.  Emperical data
	 * seems to indicate that this covers the "obviously" visible part
	 * of the disk, ie: sl->sl_ncylinders.
	 */
	sl->sl_part[SUN_RAWPART].sdkp_cyloffset = 0;
	sl->sl_part[SUN_RAWPART].sdkp_nsectors = sl->sl_ncylinders * secpercyl;

	memset(buf, 0, sizeof buf);
	sunlabel_enc(buf, sl);
	write_block(fd, 0, buf, sizeof buf);

	close(fd);
	return 0;
}
Exemple #15
0
static void
write_float (st_parameter_dt *dtp, const fnode *f, const char *source, int len)
{
  GFC_REAL_LARGEST n;
  int nb =0, res, save_scale_factor;
  char * p, fin;
  fnode *f2 = NULL;

  n = extract_real (source, len);

  if (f->format != FMT_B && f->format != FMT_O && f->format != FMT_Z)
    {
      res = isfinite (n); 
      if (res == 0)
	{
	  nb =  f->u.real.w;
	  
	  /* If the field width is zero, the processor must select a width 
	     not zero.  4 is chosen to allow output of '-Inf' or '+Inf' */
	     
	  if (nb == 0) nb = 4;
	  p = write_block (dtp, nb);
          if (p == NULL)
            return;
	  if (nb < 3)
	    {
	      memset (p, '*',nb);
	      return;
	    }

	  memset(p, ' ', nb);
	  res = !isnan (n);
	  if (res != 0)
	    {
	      if (signbit(n))
	        {
	        
	          /* If the sign is negative and the width is 3, there is
	             insufficient room to output '-Inf', so output asterisks */
	             
	          if (nb == 3)
	            {
	              memset (p, '*',nb);
	              return;
	            }
	            
	          /* The negative sign is mandatory */
	            
	          fin = '-';
		}    
	      else
	      
	          /* The positive sign is optional, but we output it for
	             consistency */
	             
		  fin = '+';

	      if (nb > 8)
	      
	        /* We have room, so output 'Infinity' */
	        
		memcpy(p + nb - 8, "Infinity", 8);
	      else
	      
	        /* For the case of width equals 8, there is not enough room
	           for the sign and 'Infinity' so we go with 'Inf' */
	            
		memcpy(p + nb - 3, "Inf", 3);
	      if (nb < 9 && nb > 3)
		p[nb - 4] = fin;  /* Put the sign in front of Inf */
	      else if (nb > 8)
		p[nb - 9] = fin;  /* Put the sign in front of Infinity */
	    }
	  else
	    memcpy(p + nb - 3, "NaN", 3);
	  return;
	}
    }

  if (f->format != FMT_G)
    output_float (dtp, f, n);
  else
    {
      save_scale_factor = dtp->u.p.scale_factor;
      f2 = calculate_G_format (dtp, f, n, &nb);
      output_float (dtp, f2, n);
      dtp->u.p.scale_factor = save_scale_factor;
      if (f2 != NULL)
        free_mem(f2);

      if (nb > 0)
        {
	  p = write_block (dtp, nb);
          if (p == NULL)
            return;
          memset (p, ' ', nb);
        }
    }
}
static void
write_utf8_char4 (st_parameter_dt *dtp, gfc_char4_t *source,
		     int src_len, int w_len)
{
  char *p;
  int j, k = 0;
  gfc_char4_t c;
  static const uchar masks[6] =  { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  static const uchar limits[6] = { 0x80, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE };
  size_t nbytes;
  uchar buf[6], d, *q; 

  /* Take care of preceding blanks.  */
  if (w_len > src_len)
    {
      k = w_len - src_len;
      p = write_block (dtp, k);
      if (p == NULL)
	return;
      memset (p, ' ', k);
    }

  /* Get ready to handle delimiters if needed.  */
  switch (dtp->u.p.current_unit->delim_status)
    {
    case DELIM_APOSTROPHE:
      d = '\'';
      break;
    case DELIM_QUOTE:
      d = '"';
      break;
    default:
      d = ' ';
      break;
    }

  /* Now process the remaining characters, one at a time.  */
  for (j = k; j < src_len; j++)
    {
      c = source[j];
      if (c < 0x80)
	{
	  /* Handle the delimiters if any.  */
	  if (c == d && d != ' ')
	    {
	      p = write_block (dtp, 2);
	      if (p == NULL)
		return;
	      *p++ = (uchar) c;
	    }
	  else
	    {
	      p = write_block (dtp, 1);
	      if (p == NULL)
		return;
	    }
	  *p = (uchar) c;
	}
      else
	{
	  /* Convert to UTF-8 sequence.  */
	  nbytes = 1;
	  q = &buf[6];

	  do
	    {
	      *--q = ((c & 0x3F) | 0x80);
	      c >>= 6;
	      nbytes++;
	    }
	  while (c >= 0x3F || (c & limits[nbytes-1]));

	  *--q = (c | masks[nbytes-1]);

	  p = write_block (dtp, nbytes);
	  if (p == NULL)
	    return;

	  while (q < &buf[6])
	    *p++ = *q++;
	}
    }
}
Exemple #17
0
static void
write_int (st_parameter_dt *dtp, const fnode *f, const char *source, int len,
           const char *(*conv) (GFC_UINTEGER_LARGEST, char *, size_t))
{
  GFC_UINTEGER_LARGEST n = 0;
  int w, m, digits, nzero, nblank;
  char *p;
  const char *q;
  char itoa_buf[GFC_BTOA_BUF_SIZE];

  w = f->u.integer.w;
  m = f->u.integer.m;

  n = extract_uint (source, len);

  /* Special case:  */

  if (m == 0 && n == 0)
    {
      if (w == 0)
        w = 1;

      p = write_block (dtp, w);
      if (p == NULL)
        return;

      memset (p, ' ', w);
      goto done;
    }

  q = conv (n, itoa_buf, sizeof (itoa_buf));
  digits = strlen (q);

  /* Select a width if none was specified.  The idea here is to always
     print something.  */

  if (w == 0)
    w = ((digits < m) ? m : digits);

  p = write_block (dtp, w);
  if (p == NULL)
    return;

  nzero = 0;
  if (digits < m)
    nzero = m - digits;

  /* See if things will work.  */

  nblank = w - (nzero + digits);

  if (nblank < 0)
    {
      star_fill (p, w);
      goto done;
    }


  if (!dtp->u.p.no_leading_blank)
    {
      memset (p, ' ', nblank);
      p += nblank;
      memset (p, '0', nzero);
      p += nzero;
      memcpy (p, q, digits);
    }
  else
    {
      memset (p, '0', nzero);
      p += nzero;
      memcpy (p, q, digits);
      p += digits;
      memset (p, ' ', nblank);
      dtp->u.p.no_leading_blank = 0;
    }

 done:
  return;
}
void
write_a (st_parameter_dt *dtp, const fnode *f, const char *source, int len)
{
  int wlen;
  char *p;

  wlen = f->u.string.length < 0
	 || (f->format == FMT_G && f->u.string.length == 0)
	 ? len : f->u.string.length;

#ifdef HAVE_CRLF
  /* If this is formatted STREAM IO convert any embedded line feed characters
     to CR_LF on systems that use that sequence for newlines.  See F2003
     Standard sections 10.6.3 and 9.9 for further information.  */
  if (is_stream_io (dtp))
    {
      const char crlf[] = "\r\n";
      int i, q, bytes;
      q = bytes = 0;

      /* Write out any padding if needed.  */
      if (len < wlen)
	{
	  p = write_block (dtp, wlen - len);
	  if (p == NULL)
	    return;
	  memset (p, ' ', wlen - len);
	}

      /* Scan the source string looking for '\n' and convert it if found.  */
      for (i = 0; i < wlen; i++)
	{
	  if (source[i] == '\n')
	    {
	      /* Write out the previously scanned characters in the string.  */
	      if (bytes > 0)
		{
		  p = write_block (dtp, bytes);
		  if (p == NULL)
		    return;
		  memcpy (p, &source[q], bytes);
		  q += bytes;
		  bytes = 0;
		}

	      /* Write out the CR_LF sequence.  */ 
	      q++;
	      p = write_block (dtp, 2);
              if (p == NULL)
                return;
	      memcpy (p, crlf, 2);
	    }
	  else
	    bytes++;
	}

      /*  Write out any remaining bytes if no LF was found.  */
      if (bytes > 0)
	{
	  p = write_block (dtp, bytes);
	  if (p == NULL)
	    return;
	  memcpy (p, &source[q], bytes);
	}
    }
  else
    {
#endif
      p = write_block (dtp, wlen);
      if (p == NULL)
	return;

      if (wlen < len)
	memcpy (p, source, wlen);
      else
	{
	  memset (p, ' ', wlen - len);
	  memcpy (p + wlen - len, source, len);
	}
#ifdef HAVE_CRLF
    }
#endif
}
Exemple #19
0
int main(int argc, char ** argv)
{
	if (stdout_is_piped()) // other wise you don't see the seg fault
		setup_segfault_handling(argv);
	
	assert_stdin_is_piped();
	assert_stdout_is_piped();
	//assert_stdin_or_out_is_piped();
	
	static int join = INNER_JOIN;
	static char join_as_string[100] = "";
	static char right_file[1000] = "";
	static char left_column[100] = "";
	static char right_column[100] = "";
	static int debug = 0;
	
	struct Params * params = NULL;
	params = add_string_param(params, "join", 'j', join_as_string, 1);
	params = add_string_param(params, "right_file", 'f', right_file, 1);
	params = add_string_param(params, "left_column", 'l', left_column, 1);
	params = add_string_param(params, "right_column", 'r', right_column, 1);
	eval_params(params, argc, argv);
	
	if (strcmp(join_as_string, "left")==0) {
		join = LEFT_JOIN;
	} else if (strcmp(join_as_string, "inner")==0) {
		join = INNER_JOIN;
	} else if (strcmp(join_as_string, "right")==0) {
		join = RIGHT_JOIN;
	} else {
		fprintf(stderr, "invalid --join option, choices are: 'left', 'inner' or 'right'\n");
	}
	
	if (right_file[0] == 0 || left_column[0] == 0 || right_column[0] == 0)
	{
		fprintf(stderr, "Usage: cat left_table.b | ./join_inner --right_file=right_table.b --left_column=shape_row_id --right_column=first_hit_shape_row_id | ...");
		return EXIT_FAILURE;
	}
	
	FILE * fp = fopen(right_file, "r");
	if (fp == NULL)
	{
		fprintf(stderr, "right_file '%s' is invalid.\n", right_file);
		return EXIT_FAILURE;
	}
	struct Block * left_block = read_block(stdin);
	
	int left_block_join_column_id = get_column_id_by_name(left_block, left_column);
	if (left_block_join_column_id == -1) { fprintf(stderr, "%s: left_block didn't have column '%s'\n", argv[0], left_column); return EXIT_FAILURE; }
	//fprintf(stderr, "left_block_join_column_id = %d\n", left_block_join_column_id);
	
	struct Block * right_block = NULL;
	while ((right_block = read_block(fp)))
	{
		int right_block_join_column_id = get_column_id_by_name(right_block, right_column);
		//fprintf(stderr, "right_block_join_column_id = %d\n", right_block_join_column_id);
		if (right_block_join_column_id == -1) {
			fprintf(stderr, "%s: right_block didn't have column '%s'\n", argv[0], right_column);
			free_block(right_block);
			continue;
		}
		
		struct Column * left_column = get_column(left_block, left_block_join_column_id);
		struct Column * right_column = get_column(right_block, right_block_join_column_id);
		
		if (left_column->type != right_column->type || left_column->bsize != right_column->bsize) {
			fprintf(stderr, "columns found, but they do not match type or bsize\n");
			free_block(right_block);
			continue;
		}
		
		struct Block * join_block = new_block();
		join_block = copy_all_columns(join_block, left_block);
		join_block = copy_all_attributes(join_block, left_block);
		join_block = add_command(join_block, argc, argv);
		
		int num_columns_from_right_block = 0;
		int * column_ids_from_right_block = NULL;
		
		int i, j, k;
		for (i = 0 ; i < right_block->num_columns ; i++) {
			struct Column * column = get_column(right_block, i);
			if (get_column_id_by_name(join_block, column_get_name(column)) == -1) {
				//fprintf(stderr, "add %s\n", column_get_name(column));
				join_block = _add_column(join_block, column->type, column->bsize, column_get_name(column));
				num_columns_from_right_block++;
				column_ids_from_right_block = realloc(column_ids_from_right_block, sizeof(int)*num_columns_from_right_block);
				column_ids_from_right_block[num_columns_from_right_block-1] = i;
			}
		}
		
		for (i = 0 ; i < left_block->num_rows ; i++) {
			int found = 0;
			for (j = 0 ; j < right_block->num_rows ; j++) {
				if (memcmp(get_cell(left_block, i, left_block_join_column_id), get_cell(right_block, j, right_block_join_column_id), left_column->bsize)==0) {
					join_block = add_row_and_blank(join_block);
					
					for (k = 0 ; k < left_block->num_columns ; k++) {
						memcpy(get_cell(join_block, join_block->num_rows-1, k), get_cell(left_block, i, k), get_column(left_block, k)->bsize);
					}
					//memcpy(get_row(join_block, join_block->num_rows-1), get_row(left_block, i), left_block->row_bsize);
					
					for (k = 0 ; k < num_columns_from_right_block ; k++) {
						//fprintf(stderr, "copy cell %d over\n", column_ids_from_right_block[k]);
						memcpy(get_cell(join_block, join_block->num_rows-1, left_block->num_columns + k), get_cell(right_block, j, column_ids_from_right_block[k]), get_column(right_block, column_ids_from_right_block[k])->bsize);
					}
					found++;
				}
			}
			if (found == 0) {
				join_block = add_row_and_blank(join_block);
				for (k = 0 ; k < left_block->num_columns ; k++) {
					memcpy(get_cell(join_block, join_block->num_rows-1, k), get_cell(left_block, i, k), get_column(left_block, k)->bsize);
				}
			}
		}
		
		write_block(stdout, join_block);
		free_block(right_block);
		free_block(join_block);
	}
	free_block(left_block);
	fclose(fp);
}
void
write_a_char4 (st_parameter_dt *dtp, const fnode *f, const char *source, int len)
{
  int wlen;
  gfc_char4_t *q;

  wlen = f->u.string.length < 0
	 || (f->format == FMT_G && f->u.string.length == 0)
	 ? len : f->u.string.length;

  q = (gfc_char4_t *) source;
#ifdef HAVE_CRLF
  /* If this is formatted STREAM IO convert any embedded line feed characters
     to CR_LF on systems that use that sequence for newlines.  See F2003
     Standard sections 10.6.3 and 9.9 for further information.  */
  if (is_stream_io (dtp))
    {
      const char crlf[] = "\r\n";
      int i, bytes;
      gfc_char4_t *qq;
      bytes = 0;

      /* Write out any padding if needed.  */
      if (len < wlen)
	{
	  char *p;
	  p = write_block (dtp, wlen - len);
	  if (p == NULL)
	    return;
	  memset (p, ' ', wlen - len);
	}

      /* Scan the source string looking for '\n' and convert it if found.  */
      qq = (gfc_char4_t *) source;
      for (i = 0; i < wlen; i++)
	{
	  if (qq[i] == '\n')
	    {
	      /* Write out the previously scanned characters in the string.  */
	      if (bytes > 0)
		{
		  if (dtp->u.p.current_unit->flags.encoding == ENCODING_UTF8)
		    write_utf8_char4 (dtp, q, bytes, 0);
		  else
		    write_default_char4 (dtp, q, bytes, 0);
		  bytes = 0;
		}

	      /* Write out the CR_LF sequence.  */ 
	      write_default_char4 (dtp, crlf, 2, 0);
	    }
	  else
	    bytes++;
	}

      /*  Write out any remaining bytes if no LF was found.  */
      if (bytes > 0)
	{
	  if (dtp->u.p.current_unit->flags.encoding == ENCODING_UTF8)
	    write_utf8_char4 (dtp, q, bytes, 0);
	  else
	    write_default_char4 (dtp, q, bytes, 0);
	}
    }
  else
    {
#endif
      if (dtp->u.p.current_unit->flags.encoding == ENCODING_UTF8)
	write_utf8_char4 (dtp, q, len, wlen);
      else
	write_default_char4 (dtp, q, len, wlen);
#ifdef HAVE_CRLF
    }
#endif
}
Exemple #21
0
void net_send_epg(
		const char *start,
		const char *stop,
		const char *title,
		const char *desc,
		const char *lang,
		const char *category
		)
{
	size_t st;
	size_t sp;
	size_t t;
	size_t d;
	size_t l;
	size_t c;
	size_t len;
	char *epg;
	char *end;

	/* nanosleep((struct timespec[]){{0, 100000000}}, NULL); */
	assert(srv_sd > 0);
	if (NULL == start)
		return;
	if (NULL == stop)
		return;

	st = strlen(start) + 1;
	sp = strlen(stop) + 1;

	t = 1;
	if (title != NULL)
		t += strlen(title);

	d = 1;
	if (desc != NULL)
		d += strlen(desc);

    l = 1;
    if (lang != NULL)
        l += strlen(lang);

    c = 1;
    if (category != NULL)
        c += strlen(category);

    len = st + sp + t + d + l + c;

	epg = (char *) calloc(len, sizeof(char));
	if (NULL == epg)
		return;

	end = epg;

	memcpy(end, start, st);
	end += st;

	memcpy(end, stop, sp);
	end += sp;

	if (title != NULL)
		memcpy(end, title, t);
	end += t;

	if (desc != NULL)
		memcpy(end, desc, d);
	end += d;

    if (lang != NULL)
        memcpy(end, lang, l);
    end += l;

    if (category != NULL)
        memcpy(end, category, c);
    end += c;

#if DEBUG_OUT
	fprintf(stderr, "[C] Sending EPG: %u bytes\n", len);
#endif

	if (write_block(srv_sd, EPG_DATA, epg, len) <= 0)
		fprintf(stderr, "Can't send EPG data\n");

    	free(epg);

	return;
}
static void
write_decimal (st_parameter_dt *dtp, const fnode *f, const char *source,
	       int len,
               const char *(*conv) (GFC_INTEGER_LARGEST, char *, size_t))
{
  GFC_INTEGER_LARGEST n = 0;
  int w, m, digits, nsign, nzero, nblank;
  char *p;
  const char *q;
  sign_t sign;
  char itoa_buf[GFC_BTOA_BUF_SIZE];

  w = f->u.integer.w;
  m = f->format == FMT_G ? -1 : f->u.integer.m;

  n = extract_int (source, len);

  /* Special case:  */
  if (m == 0 && n == 0)
    {
      if (w == 0)
        w = 1;

      p = write_block (dtp, w);
      if (p == NULL)
        return;

      memset (p, ' ', w);
      goto done;
    }

  sign = calculate_sign (dtp, n < 0);
  if (n < 0)
    n = -n;
  nsign = sign == S_NONE ? 0 : 1;
  
  /* conv calls gfc_itoa which sets the negative sign needed
     by write_integer. The sign '+' or '-' is set below based on sign
     calculated above, so we just point past the sign in the string
     before proceeding to avoid double signs in corner cases.
     (see PR38504)  */
  q = conv (n, itoa_buf, sizeof (itoa_buf));
  if (*q == '-')
    q++;

  digits = strlen (q);

  /* Select a width if none was specified.  The idea here is to always
     print something.  */

  if (w == 0)
    w = ((digits < m) ? m : digits) + nsign;

  p = write_block (dtp, w);
  if (p == NULL)
    return;

  nzero = 0;
  if (digits < m)
    nzero = m - digits;

  /* See if things will work.  */

  nblank = w - (nsign + nzero + digits);

  if (nblank < 0)
    {
      star_fill (p, w);
      goto done;
    }

  memset (p, ' ', nblank);
  p += nblank;

  switch (sign)
    {
    case S_PLUS:
      *p++ = '+';
      break;
    case S_MINUS:
      *p++ = '-';
      break;
    case S_NONE:
      break;
    }

  memset (p, '0', nzero);
  p += nzero;

  memcpy (p, q, digits);

 done:
  return;
}
Exemple #23
0
bool CVechileMgr::SendLocationPos( _stVechile *p , int ncount )
{
	if( ncount <= 0 || p == NULL ) {
		return false ;
	}

	time_t now = share::Util::currentTimeUsec() ;
	srand( now ) ;
	int nrand = rand() ;  // 产生随机报警

	DataBuffer buf ;

	TermLocationHeader  header ;
	BuildHeader( header.header, 0x200 , sizeof(GpsInfo), p ) ;

	unsigned int alarm = 0 ;
	if ( now - p->last_alam_  > _alam_time && _alam_time > 0 ) {
		alarm = htonl( nrand ) ;
		p->last_alam_ = now ;
	}
	memcpy( &header.gpsinfo.alarm, &alarm, sizeof(unsigned int) ) ;

	unsigned int state = 0 ;
	memcpy( &header.gpsinfo.state , &state, sizeof(unsigned int) ) ;

	int pos = p->gps_pos_ ;
	pos = pos + 1 ;
	pos = pos % ncount ;

	Point &pt = _gps_vec[pos] ;

	header.gpsinfo.heigth    = htons(nrand%100) ;
	header.gpsinfo.speed     = htons(get_car_speed());//htons(nrand%1000)  ;
	header.gpsinfo.direction = htons(nrand%360) ;
	// 取得当前BCD的时间
	get_bcd_time( header.gpsinfo.date_time ) ;

	if(header.gpsinfo.speed == 0) {
		header.gpsinfo.state.bit6 = 0;
		header.gpsinfo.state.bit7 = 0;
		header.gpsinfo.longitude = 0 ;
		header.gpsinfo.latitude  = 0 ;
	} else {
		header.gpsinfo.state.bit6 = 1;
		header.gpsinfo.state.bit7 = 1;
		header.gpsinfo.longitude = htonl( pt.lon ) ;
		header.gpsinfo.latitude  = htonl( pt.lat ) ;
	}

	buf.writeBlock( &header, sizeof(header) ) ;

	// 需要上传CAN的数据
	if ( now - p->last_candata_ > _candata_time && _candata_time > 0 ) {

		p->last_candata_ = now ;

		int index = nrand % 5;

		write_dword( buf, 0x01, 2000 ) ;
		write_word(  buf, 0x02, 100 ) ;
		write_word(  buf, 0x03, 800 ) ;
		if ( index != 0 ) {
			struct _B1{
				unsigned char cmd ;
				unsigned int  val ;
			};
			_B1 b1 ;
			b1.cmd = ( index - 1 ) ;
			b1.val = htonl( nrand ) ;

			write_block( buf, 0x11, (unsigned char*)&b1 , sizeof(_B1) ) ;
		} else {
			write_byte( buf, 0x11, 0 ) ;
		}

		if ( nrand % 2 == 0 ) {
			struct _B2{
				unsigned char type;
				unsigned int  val ;
				unsigned char dir ;
			};
			_B2 b2 ;
			b2.type = (( index + 1 ) % 5 ) ;
			b2.val  = htonl( index ) ;
			b2.dir  = ( index%2 == 0 ) ;

			write_block( buf, 0x12, (unsigned char*)&b2, sizeof(_B2) ) ;
		}
		if ( nrand % 3 == 0 ) {
			struct _B3{
				unsigned int   id ;
				unsigned short time ;
				unsigned char  result ;
			};
			_B3 b3 ;
			b3.id     = htonl( index ) ;
			b3.time   = htons( nrand % 100 ) ;
			b3.result = ( index % 2 == 0 ) ;

			write_block( buf , 0x13, (unsigned char*)&b3, sizeof(_B3) ) ;
		}

		switch( index ) {
		case 0:
			write_word(  buf, 0x20, nrand ) ;
			write_word(  buf, 0x21, nrand % 100 ) ;
			write_word(  buf, 0x22, nrand % 1000 ) ;
			write_word(  buf, 0x23, nrand % 80 ) ;
		case 1:
			write_dword( buf, 0x24, nrand % 157887 ) ;
			write_dword( buf, 0x25, nrand % 233555 ) ;
			write_dword( buf, 0x26, nrand % 200 ) ;
			write_dword( buf, 0x40, nrand % 3000 ) ;
		case 2:
			write_word(  buf, 0x41, nrand % 130 ) ;
			write_word(  buf, 0x42, nrand % 120 ) ;
			write_word(  buf, 0x43, nrand % 200 ) ;
			write_word(  buf, 0x44, nrand % 300 ) ;
		case 3:
			write_word(  buf, 0x45, nrand % 150 ) ;
			write_word(  buf, 0x46, nrand % 100 ) ;
		case 4:
			write_word(  buf, 0x47, nrand % 150 ) ;
			write_word(  buf, 0x48, nrand % 200 ) ;
			break ;
		}
	}

	// 长度为消息内容的长度去掉头和尾
	unsigned short  mlen = (buf.getLength()-sizeof(GBheader)) & 0x03FF ;
	buf.fillInt16( mlen, 3 ) ;

	GBFooter footer ;
	buf.writeBlock( &footer, sizeof(footer) ) ;

	if ( Send5BData( p->fd_, buf.getBuffer(), buf.getLength() ) ) {
		p->gps_pos_ = pos ;
		return true ;
	}
	p->car_state_ = OFF_LINE ;
	// 发送位置包
	return false ;
}
static void
write_character (st_parameter_dt *dtp, const char *source, int kind, int length)
{
  int i, extra;
  char *p, d;

  switch (dtp->u.p.current_unit->delim_status)
    {
    case DELIM_APOSTROPHE:
      d = '\'';
      break;
    case DELIM_QUOTE:
      d = '"';
      break;
    default:
      d = ' ';
      break;
    }

  if (kind == 1)
    {
      if (d == ' ')
	extra = 0;
      else
	{
	  extra = 2;

	  for (i = 0; i < length; i++)
	    if (source[i] == d)
	      extra++;
	}

      p = write_block (dtp, length + extra);
      if (p == NULL)
	return;

      if (d == ' ')
	memcpy (p, source, length);
      else
	{
	  *p++ = d;

	  for (i = 0; i < length; i++)
            {
              *p++ = source[i];
              if (source[i] == d)
		*p++ = d;
	    }

	  *p = d;
	}
    }
  else
    {
      if (d == ' ')
	{
	  if (dtp->u.p.current_unit->flags.encoding == ENCODING_UTF8)
	    write_utf8_char4 (dtp, (gfc_char4_t *) source, length, 0);
	  else
	    write_default_char4 (dtp, (gfc_char4_t *) source, length, 0);
	}
      else
	{
	  p = write_block (dtp, 1);
	  *p = d;

	  if (dtp->u.p.current_unit->flags.encoding == ENCODING_UTF8)
	    write_utf8_char4 (dtp, (gfc_char4_t *) source, length, 0);
	  else
	    write_default_char4 (dtp, (gfc_char4_t *) source, length, 0);

	  p = write_block (dtp, 1);
	  *p = d;
	}
    }
}
/*
 * Hard codes the following directory structure:
 * root
 *   foo1 50  (Directory block 0) - NOTE: no actual directory file created
 *   foo2 60,70  (Directory block 1)
 *     bar1 80 (Directory block 1_1)
 *     hello.txt 100 (File block 1)
 */
void test_file_operations_setup() {
  size_of_disk = dev_open();
  
  if (size_of_disk != 250000) {
    printf("\ntest_file_operations_setup FAIL.  Size of disk must be 250,000 blocks.\n");
  }
  
  my_mkfs();
  
  // Zero out buffers
  char buffer[BLOCKSIZE];
  char *buffer_ptr = buffer;
  char name[MAX_FILE_NAME_LENGTH];
  
  /** ROOT BLOCK **/  
  unsigned short bytes_allocated = HEADER_SIZE + 2 * FILE_NUM_PAIRINGS_SIZE;
  
  populate_file_header(buffer, ROOT_BLOCK, bytes_allocated, 'd');
  
  // Set directory one name and block number
  memset(name, 0, MAX_FILE_NAME_LENGTH);
  strcpy(name, "foo1");
  buffer_ptr += HEADER_SIZE;
  memcpy(buffer_ptr, name, MAX_FILE_NAME_LENGTH);
  
  unsigned int block_num = DIRECTORY_BLOCK_0;
  buffer_ptr += MAX_FILE_NAME_LENGTH;
  memcpy(buffer_ptr, &block_num, BYTES_IN_INT);
  
  // Set directory two name and block number
  memset(name, 0, MAX_FILE_NAME_LENGTH);
  buffer_ptr += BYTES_IN_INT;
  strcpy(name, "foo2");
  memcpy(buffer_ptr, name, MAX_FILE_NAME_LENGTH);
  
  block_num = DIRECTORY_BLOCK_1;
  buffer_ptr += MAX_FILE_NAME_LENGTH;
  memcpy(buffer_ptr, &block_num, BYTES_IN_INT);

  write_block(ROOT_BLOCK, buffer);
  setBlockInBitmapToStatus (1, ROOT_BLOCK);
  
  /** DIRECTORY 1 **/
  bytes_allocated = HEADER_SIZE + 1 * FILE_NUM_PAIRINGS_SIZE;
    
  populate_file_header(buffer, DIRECTORY_BLOCK_1_NEXT_BLOCK, bytes_allocated, 'd');
  
  // Set directory one name and block number
  memset(name, 0, MAX_FILE_NAME_LENGTH);
  strcpy(name, "bar1");
  buffer_ptr = buffer;
  buffer_ptr += HEADER_SIZE;
  memcpy(buffer_ptr, name, MAX_FILE_NAME_LENGTH);
  
  block_num = DIRECTORY_BLOCK_1_1;
  buffer_ptr += MAX_FILE_NAME_LENGTH;
  memcpy(buffer_ptr, &block_num, BYTES_IN_INT);

  write_block(DIRECTORY_BLOCK_1, buffer);
  setBlockInBitmapToStatus (1, DIRECTORY_BLOCK_1);
  
  
  /** DIRECTORY 1_NEXT_BLOCK **/
  bytes_allocated = HEADER_SIZE + 1 * FILE_NUM_PAIRINGS_SIZE;
    
  populate_file_header(buffer, ROOT_BLOCK, bytes_allocated, 'd');
  
  // Set directory one name and block number
  memset(name, 0, MAX_FILE_NAME_LENGTH);
  strcpy(name, "hello.txt");
  buffer_ptr = buffer;
  buffer_ptr += HEADER_SIZE;
  memcpy(buffer_ptr, name, MAX_FILE_NAME_LENGTH);
  
  block_num = FILE_BLOCK_1;
  buffer_ptr += MAX_FILE_NAME_LENGTH;
  memcpy(buffer_ptr, &block_num, BYTES_IN_INT);

  write_block(DIRECTORY_BLOCK_1_NEXT_BLOCK, buffer);
  setBlockInBitmapToStatus (1, DIRECTORY_BLOCK_1_NEXT_BLOCK);
  
  /** DIRECTORY 1_1 **/
  bytes_allocated = HEADER_SIZE;
    
  populate_file_header(buffer, ROOT_BLOCK, bytes_allocated, 'd');
  
  // Set directory one name and block number
  write_block(DIRECTORY_BLOCK_1_1, buffer);
  setBlockInBitmapToStatus (1, DIRECTORY_BLOCK_1_1);
}
Exemple #26
0
static void
write_decimal (st_parameter_dt *dtp, const fnode *f, const char *source,
	       int len,
               const char *(*conv) (GFC_INTEGER_LARGEST, char *, size_t))
{
  GFC_INTEGER_LARGEST n = 0;
  int w, m, digits, nsign, nzero, nblank;
  char *p;
  const char *q;
  sign_t sign;
  char itoa_buf[GFC_BTOA_BUF_SIZE];

  w = f->u.integer.w;
  m = f->u.integer.m;

  n = extract_int (source, len);

  /* Special case:  */

  if (m == 0 && n == 0)
    {
      if (w == 0)
        w = 1;

      p = write_block (dtp, w);
      if (p == NULL)
        return;

      memset (p, ' ', w);
      goto done;
    }

  sign = calculate_sign (dtp, n < 0);
  if (n < 0)
    n = -n;

  nsign = sign == SIGN_NONE ? 0 : 1;
  q = conv (n, itoa_buf, sizeof (itoa_buf));

  digits = strlen (q);

  /* Select a width if none was specified.  The idea here is to always
     print something.  */

  if (w == 0)
    w = ((digits < m) ? m : digits) + nsign;

  p = write_block (dtp, w);
  if (p == NULL)
    return;

  nzero = 0;
  if (digits < m)
    nzero = m - digits;

  /* See if things will work.  */

  nblank = w - (nsign + nzero + digits);

  if (nblank < 0)
    {
      star_fill (p, w);
      goto done;
    }

  memset (p, ' ', nblank);
  p += nblank;

  switch (sign)
    {
    case SIGN_PLUS:
      *p++ = '+';
      break;
    case SIGN_MINUS:
      *p++ = '-';
      break;
    case SIGN_NONE:
      break;
    }

  memset (p, '0', nzero);
  p += nzero;

  memcpy (p, q, digits);

 done:
  return;
}
Exemple #27
0
void
Record_DS::disk_thread ( void )
{
    _thread.name( "Capture" );

    DMESSAGE( "capture thread running..." );

    const nframes_t nframes = _nframes;

    /* buffer to hold the interleaved data returned by the track reader */
    sample_t *buf = buffer_alloc( nframes * channels() * _disk_io_blocks );
    sample_t *cbuf = buffer_alloc( nframes );

    const size_t block_size = nframes * sizeof( sample_t );

    nframes_t blocks_read = 0;

    while ( wait_for_block() )
    {
        /* pull data from the per-channel ringbuffers and interlace it */
        for ( int i = channels(); i--; )
        {
            while ( jack_ringbuffer_read_space( _rb[ i ] ) < block_size )
                usleep( 10 * 1000 );

            jack_ringbuffer_read( _rb[ i ], ((char*)cbuf), block_size );
            
            buffer_interleave_one_channel( buf + ( blocks_read * nframes * channels() ),
                                           cbuf, 
                                           i,
                                           channels(),
                                           nframes );
        }

        blocks_read++;

        if ( blocks_read == _disk_io_blocks )
        {
            write_block( buf, nframes * _disk_io_blocks );
            blocks_read = 0;
        }
    }

    DMESSAGE( "capture thread terminating" );

    /* flush what remains in the buffer out to disk */

    {
        while ( blocks_read-- > 0 || ( ! sem_trywait( &_blocks ) && errno != EAGAIN ) )
        {
            for ( int i = channels(); i--; )
            {
                jack_ringbuffer_read( _rb[ i ], (char*)cbuf, block_size );

                buffer_interleave_one_channel( buf, cbuf, i, channels(), nframes );
            }

            const nframes_t frames_remaining = (_stop_frame - _frame ) - _frames_written;

            if ( frames_remaining < nframes )
            {
                /* this is the last block, might be partial  */
                write_block( buf, frames_remaining );
                break;
            }
            else
                write_block( buf, nframes );
        }
    }

    free(buf);
    free(cbuf);

    DMESSAGE( "finalzing capture" );

    Track::Capture *c = _capture;

    _capture = NULL;

    /* now finalize the recording */

    if ( c->audio_file )
        track()->finalize( c, _stop_frame );

    delete c;

    flush();

    _terminate = false;

    DMESSAGE( "capture thread gone" );

    _thread.exit();
}
Exemple #28
0
static void
output_float (st_parameter_dt *dtp, const fnode *f, GFC_REAL_LARGEST value)
{
#if defined(HAVE_GFC_REAL_16) && __LDBL_DIG__ > 18
# define MIN_FIELD_WIDTH 46
#else
# define MIN_FIELD_WIDTH 31
#endif
#define STR(x) STR1(x)
#define STR1(x) #x
  /* This must be large enough to accurately hold any value.  */
  char buffer[MIN_FIELD_WIDTH+1];
  char *out;
  char *digits;
  int e;
  char expchar;
  format_token ft;
  int w;
  int d;
  int edigits;
  int ndigits;
  /* Number of digits before the decimal point.  */
  int nbefore;
  /* Number of zeros after the decimal point.  */
  int nzero;
  /* Number of digits after the decimal point.  */
  int nafter;
  /* Number of zeros after the decimal point, whatever the precision.  */
  int nzero_real;
  int leadzero;
  int nblanks;
  int i;
  sign_t sign;
  double abslog;

  ft = f->format;
  w = f->u.real.w;
  d = f->u.real.d;

  nzero_real = -1;


  /* We should always know the field width and precision.  */
  if (d < 0)
    internal_error (&dtp->common, "Unspecified precision");

  /* Use sprintf to print the number in the format +D.DDDDe+ddd
     For an N digit exponent, this gives us (MIN_FIELD_WIDTH-5)-N digits
     after the decimal point, plus another one before the decimal point.  */
  sign = calculate_sign (dtp, value < 0.0);
  if (value < 0)
    value = -value;

  /* Printf always prints at least two exponent digits.  */
  if (value == 0)
    edigits = 2;
  else
    {
#if defined(HAVE_GFC_REAL_10) || defined(HAVE_GFC_REAL_16)
      abslog = fabs((double) log10l(value));
#else
      abslog = fabs(log10(value));
#endif
      if (abslog < 100)
	edigits = 2;
      else
        edigits = 1 + (int) log10(abslog);
    }

  if (ft == FMT_F || ft == FMT_EN
      || ((ft == FMT_D || ft == FMT_E) && dtp->u.p.scale_factor != 0))
    {
      /* Always convert at full precision to avoid double rounding.  */
      ndigits = MIN_FIELD_WIDTH - 4 - edigits;
    }
  else
    {
      /* We know the number of digits, so can let printf do the rounding
	 for us.  */
      if (ft == FMT_ES)
	ndigits = d + 1;
      else
	ndigits = d;
      if (ndigits > MIN_FIELD_WIDTH - 4 - edigits)
	ndigits = MIN_FIELD_WIDTH - 4 - edigits;
    }

  /* #   The result will always contain a decimal point, even if no
   *     digits follow it
   *
   * -   The converted value is to be left adjusted on the field boundary
   *
   * +   A sign (+ or -) always be placed before a number
   *
   * MIN_FIELD_WIDTH  minimum field width
   *
   * *   (ndigits-1) is used as the precision
   *
   *   e format: [-]d.ddde±dd where there is one digit before the
   *   decimal-point character and the number of digits after it is
   *   equal to the precision. The exponent always contains at least two
   *   digits; if the value is zero, the exponent is 00.
   */
  sprintf (buffer, "%+-#" STR(MIN_FIELD_WIDTH) ".*"
	   GFC_REAL_LARGEST_FORMAT "e", ndigits - 1, value);

  /* Check the resulting string has punctuation in the correct places.  */
  if (d != 0 && (buffer[2] != '.' || buffer[ndigits + 2] != 'e'))
      internal_error (&dtp->common, "printf is broken");

  /* Read the exponent back in.  */
  e = atoi (&buffer[ndigits + 3]) + 1;

  /* Make sure zero comes out as 0.0e0.  */
  if (value == 0.0)
    e = 0;

  /* Normalize the fractional component.  */
  buffer[2] = buffer[1];
  digits = &buffer[2];

  /* Figure out where to place the decimal point.  */
  switch (ft)
    {
    case FMT_F:
      nbefore = e + dtp->u.p.scale_factor;
      if (nbefore < 0)
	{
	  nzero = -nbefore;
          nzero_real = nzero;
	  if (nzero > d)
	    nzero = d;
	  nafter = d - nzero;
	  nbefore = 0;
	}
      else
	{
	  nzero = 0;
	  nafter = d;
	}
      expchar = 0;
      break;

    case FMT_E:
    case FMT_D:
      i = dtp->u.p.scale_factor;
      if (value != 0.0)
	e -= i;
      if (i < 0)
	{
	  nbefore = 0;
	  nzero = -i;
	  nafter = d + i;
	}
      else if (i > 0)
	{
	  nbefore = i;
	  nzero = 0;
	  nafter = (d - i) + 1;
	}
      else /* i == 0 */
	{
	  nbefore = 0;
	  nzero = 0;
	  nafter = d;
	}

      if (ft == FMT_E)
	expchar = 'E';
      else
	expchar = 'D';
      break;

    case FMT_EN:
      /* The exponent must be a multiple of three, with 1-3 digits before
	 the decimal point.  */
      if (value != 0.0)
        e--;
      if (e >= 0)
	nbefore = e % 3;
      else
	{
	  nbefore = (-e) % 3;
	  if (nbefore != 0)
	    nbefore = 3 - nbefore;
	}
      e -= nbefore;
      nbefore++;
      nzero = 0;
      nafter = d;
      expchar = 'E';
      break;

    case FMT_ES:
      if (value != 0.0)
        e--;
      nbefore = 1;
      nzero = 0;
      nafter = d;
      expchar = 'E';
      break;

    default:
      /* Should never happen.  */
      internal_error (&dtp->common, "Unexpected format token");
    }

  /* Round the value.  */
  if (nbefore + nafter == 0)
    {
      ndigits = 0;
      if (nzero_real == d && digits[0] >= '5')
        {
          /* We rounded to zero but shouldn't have */
          nzero--;
          nafter = 1;
          digits[0] = '1';
          ndigits = 1;
        }
    }
  else if (nbefore + nafter < ndigits)
    {
      ndigits = nbefore + nafter;
      i = ndigits;
      if (digits[i] >= '5')
	{
	  /* Propagate the carry.  */
	  for (i--; i >= 0; i--)
	    {
	      if (digits[i] != '9')
		{
		  digits[i]++;
		  break;
		}
	      digits[i] = '0';
	    }

	  if (i < 0)
	    {
	      /* The carry overflowed.  Fortunately we have some spare space
		 at the start of the buffer.  We may discard some digits, but
		 this is ok because we already know they are zero.  */
	      digits--;
	      digits[0] = '1';
	      if (ft == FMT_F)
		{
		  if (nzero > 0)
		    {
		      nzero--;
		      nafter++;
		    }
		  else
		    nbefore++;
		}
	      else if (ft == FMT_EN)
		{
		  nbefore++;
		  if (nbefore == 4)
		    {
		      nbefore = 1;
		      e += 3;
		    }
		}
	      else
		e++;
	    }
	}
    }

  /* Calculate the format of the exponent field.  */
  if (expchar)
    {
      edigits = 1;
      for (i = abs (e); i >= 10; i /= 10)
	edigits++;

      if (f->u.real.e < 0)
	{
	  /* Width not specified.  Must be no more than 3 digits.  */
	  if (e > 999 || e < -999)
	    edigits = -1;
	  else
	    {
	      edigits = 4;
	      if (e > 99 || e < -99)
		expchar = ' ';
	    }
	}
      else
	{
	  /* Exponent width specified, check it is wide enough.  */
	  if (edigits > f->u.real.e)
	    edigits = -1;
	  else
	    edigits = f->u.real.e + 2;
	}
    }
  else
    edigits = 0;

  /* Pick a field size if none was specified.  */
  if (w <= 0)
    w = nbefore + nzero + nafter + (sign != SIGN_NONE ? 2 : 1);

  /* Create the ouput buffer.  */
  out = write_block (dtp, w);
  if (out == NULL)
    return;

  /* Zero values always output as positive, even if the value was negative
     before rounding.  */
  for (i = 0; i < ndigits; i++)
    {
      if (digits[i] != '0')
	break;
    }
  if (i == ndigits)
    sign = calculate_sign (dtp, 0);

  /* Work out how much padding is needed.  */
  nblanks = w - (nbefore + nzero + nafter + edigits + 1);
  if (sign != SIGN_NONE)
    nblanks--;

  /* Check the value fits in the specified field width.  */
  if (nblanks < 0 || edigits == -1)
    {
      star_fill (out, w);
      return;
    }

  /* See if we have space for a zero before the decimal point.  */
  if (nbefore == 0 && nblanks > 0)
    {
      leadzero = 1;
      nblanks--;
    }
  else
    leadzero = 0;

  /* Pad to full field width.  */


  if ( ( nblanks > 0 ) && !dtp->u.p.no_leading_blank)
    {
      memset (out, ' ', nblanks);
      out += nblanks;
    }

  /* Output the initial sign (if any).  */
  if (sign == SIGN_PLUS)
    *(out++) = '+';
  else if (sign == SIGN_MINUS)
    *(out++) = '-';

  /* Output an optional leading zero.  */
  if (leadzero)
    *(out++) = '0';

  /* Output the part before the decimal point, padding with zeros.  */
  if (nbefore > 0)
    {
      if (nbefore > ndigits)
	i = ndigits;
      else
	i = nbefore;

      memcpy (out, digits, i);
      while (i < nbefore)
	out[i++] = '0';

      digits += i;
      ndigits -= i;
      out += nbefore;
    }
  /* Output the decimal point.  */
  *(out++) = '.';

  /* Output leading zeros after the decimal point.  */
  if (nzero > 0)
    {
      for (i = 0; i < nzero; i++)
	*(out++) = '0';
    }

  /* Output digits after the decimal point, padding with zeros.  */
  if (nafter > 0)
    {
      if (nafter > ndigits)
	i = ndigits;
      else
	i = nafter;

      memcpy (out, digits, i);
      while (i < nafter)
	out[i++] = '0';

      digits += i;
      ndigits -= i;
      out += nafter;
    }

  /* Output the exponent.  */
  if (expchar)
    {
      if (expchar != ' ')
	{
	  *(out++) = expchar;
	  edigits--;
	}
#if HAVE_SNPRINTF
      snprintf (buffer, sizeof (buffer), "%+0*d", edigits, e);
#else
      sprintf (buffer, "%+0*d", edigits, e);
#endif
      memcpy (out, buffer, edigits);
    }

  if (dtp->u.p.no_leading_blank)
    {
      out += edigits;
      memset( out , ' ' , nblanks );
      dtp->u.p.no_leading_blank = 0;
    }
#undef STR
#undef STR1
#undef MIN_FIELD_WIDTH
}
Exemple #29
0
static void
flush_cache_inode(struct sfs_fs *sfs, struct cache_inode *ci) {
    write_block(sfs, &(ci->inode), sizeof(ci->inode), ci->ino);
}
Exemple #30
0
int ft847_set_mode(RIG *rig, vfo_t vfo, rmode_t mode, pbwidth_t width) {
  unsigned char cmd_index;	/* index of sequence to send */
  struct rig_state *rs = &rig->state;
  unsigned char p_cmd[YAESU_CMD_LENGTH]; /* sequence to send */
  int ret;

  /*
   * translate mode from generic to ft847 specific
   */

  rig_debug(RIG_DEBUG_VERBOSE,"ft847: generic mode = %x \n", mode);

  if (rig->caps->rig_model == RIG_MODEL_FT847UNI) {
    struct ft847_priv_data *priv = (struct ft847_priv_data*)rig->state.priv;
    priv->mode = mode;
    priv->width = width;
  }


  switch(mode) {
  case RIG_MODE_AM:
    cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_AM;
    break;
  case RIG_MODE_CW:
    cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_CW;
    break;
  case RIG_MODE_CWR:
    cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_CWR;
    break;
  case RIG_MODE_USB:
    cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_USB;
    break;
  case RIG_MODE_LSB:
    cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_LSB;
    break;
  case RIG_MODE_FM:
    cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_FM;
    break;
  default:
    return -RIG_EINVAL;		/* sorry, wrong MODE */
  }


  /*
   * Now set width
   */
  if (width != RIG_PASSBAND_NOCHANGE) {
    if (width == rig_passband_narrow(rig, mode)) {
      switch(mode) {
      case RIG_MODE_AM:
        cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_AMN;
        break;
      case RIG_MODE_FM:
        cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_FMN;
        break;
      case RIG_MODE_CW:
        cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_CWN;
        break;
      case RIG_MODE_CWR:
        cmd_index = FT_847_NATIVE_CAT_SET_MODE_MAIN_CWRN;
        break;
      case RIG_MODE_USB:
      case RIG_MODE_LSB:
        break;
      default:
        rig_debug(RIG_DEBUG_ERR,"%s: unsupported mode/width: %s/%d, narrow: %d\n",
                  __FUNCTION__, rig_strrmode(mode), width,
                  rig_passband_narrow(rig, mode));
        return -RIG_EINVAL;		/* sorry, wrong MODE/WIDTH combo  */
      }
    } else {
  		if (width != RIG_PASSBAND_NORMAL &&
          width != rig_passband_normal(rig, mode)) {
        rig_debug(RIG_DEBUG_ERR,"%s: unsupported mode/width: %s/%d, narrow: %d\n",
                  __FUNCTION__, rig_strrmode(mode), width,
                  rig_passband_narrow(rig, mode));
        return -RIG_EINVAL;		/* sorry, wrong MODE/WIDTH combo  */
      }
    }
  }

  /*
   * Now send the command
   */
  ret = opcode_vfo(rig, p_cmd, cmd_index, vfo);
  if (ret != RIG_OK)
	  return ret;

  return write_block(&rs->rigport, (char*)p_cmd, YAESU_CMD_LENGTH);
}