当前位置: 首页>>代码示例>>C++>>正文


C++ read函数代码示例

本文整理汇总了C++中read函数的典型用法代码示例。如果您正苦于以下问题:C++ read函数的具体用法?C++ read怎么用?C++ read使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了read函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: sysnet_interface_read

int sysnet_interface_read(VPNInterface *i, void *data, size_t size)
{
    return read(i->fd, data, size);
}
开发者ID:Ansa89,项目名称:toxvpn-1,代码行数:4,代码来源:sys_interface_linux.c

示例2: masterconn_findlastlogversion

void masterconn_findlastlogversion(void) {
	struct stat st;
	uint8_t buff[32800];	// 32800 = 32768 + 32
	uint64_t size;
	uint32_t buffpos;
	uint64_t lastnewline;
	int fd;

	lastlogversion = 0;

	if (stat("metadata_ml.mfs.back",&st)<0 || st.st_size==0 || (st.st_mode & S_IFMT)!=S_IFREG) {
		return;
	}

	fd = open("changelog_ml.0.back",O_RDWR);
	if (fd<0) {
		return;
	}
	fstat(fd,&st);
	size = st.st_size;
	memset(buff,0,32);
	lastnewline = 0;
	while (size>0 && size+200000>(uint64_t)(st.st_size)) {
		if (size>32768) {
			memcpy(buff+32768,buff,32);
			size-=32768;
			lseek(fd,size,SEEK_SET);
			if (read(fd,buff,32768)!=32768) {
				lastlogversion = 0;
				close(fd);
				return;
			}
			buffpos = 32768;
		} else {
			memmove(buff+size,buff,32);
			lseek(fd,0,SEEK_SET);
			if (read(fd,buff,size)!=(ssize_t)size) {
				lastlogversion = 0;
				close(fd);
				return;
			}
			buffpos = size;
			size = 0;
		}
		// size = position in file of first byte in buff
		// buffpos = position of last byte in buff to search
		while (buffpos>0) {
			buffpos--;
			if (buff[buffpos]=='\n') {
				if (lastnewline==0) {
					lastnewline = size + buffpos;
				} else {
					if (lastnewline+1 != (uint64_t)(st.st_size)) {	// garbage at the end of file - truncate
						if (ftruncate(fd,lastnewline+1)<0) {
							lastlogversion = 0;
							close(fd);
							return;
						}
					}
					buffpos++;
					while (buffpos<32800 && buff[buffpos]>='0' && buff[buffpos]<='9') {
						lastlogversion *= 10;
						lastlogversion += buff[buffpos]-'0';
						buffpos++;
					}
					if (buffpos==32800 || buff[buffpos]!=':') {
						lastlogversion = 0;
					}
					close(fd);
					return;
				}
			}
		}
	}
	close(fd);
	return;
}
开发者ID:davies,项目名称:moosefs,代码行数:77,代码来源:masterconn.c

示例3: shellh_cp_file

// Helper: copy one file to another file
// Return 1 for success, 0 for error
int shellh_cp_file( const char *psrcname, const char *pdestname, int flags )
{
  int fds = -1, fdd = -1;
  int res = 0;
  char *buf = NULL;
  ssize_t datalen, datawrote;
  u32 total = 0;
  p_logf plog = ( flags & SHELL_F_SILENT ) ? shellh_dummy_printf : printf;

  if( !strcasecmp( psrcname, pdestname ) )
  {
    plog( "Cannot copy '%s' into itself.\n", psrcname );
    goto done;
  }
  // If operation confirmation is enabled, ask the user first
  if( flags & SHELL_F_ASK_CONFIRMATION )
  {
    printf( "Copy '%s' to '%s' ? [y/n] ", psrcname, pdestname );
    if( shellh_ask_yes_no( NULL ) == 0 )
      goto done;
  }
  // Open source file
  if( ( fds = open( psrcname, O_RDONLY, 0 ) ) == -1 )
  {
    plog( "Error: unable to open source file '%s'\n", psrcname );
    goto done;
  }
  // If the destination exists and we need to ask for confirmation, do it now
  if( ( flags & SHELL_F_FORCE_DESTINATION ) == 0 )
  {
    if( ( fdd = open( pdestname, O_RDONLY, 0 ) ) != -1 )
    {
      close( fdd );
      fdd = -1;
      printf( "Destination '%s' already exists, are you sure you want to overwrite it ? [y/n] ", pdestname );
      if( shellh_ask_yes_no( NULL ) == 0 )
        goto done;
    }
  }
  // Allocate buffer
  if( ( buf = ( char* )malloc( SHELL_COPY_BUFSIZE ) ) == NULL )
  {
    plog( "ERROR: unable to allocate buffer for copy operation.\n" );
    goto done;
  }
  plog( "Copying '%s' to '%s' ... ", psrcname, pdestname );
  if( ( flags & SHELL_F_SIMULATE_ONLY ) == 0 )
  {
    // Open destination file
    if( ( fdd = open( pdestname, O_WRONLY | O_CREAT | O_TRUNC, 0 ) ) == -1 )
    {
      plog( "ERROR: unable to open '%s' for writing.\n", pdestname );
      goto done;
    }
    // Do the actual copy
    while( 1 )
    {
      if( ( datalen = read( fds, buf, SHELL_COPY_BUFSIZE ) ) == -1 )
      {
        plog( "Error reading source file '%s'.\n", psrcname );
        goto done;
      }
      if( ( datawrote = write( fdd, buf, datalen ) ) == -1 )
      {
        plog( "Error writing destination file '%s'.\n", pdestname );
        goto done;
      }
      if( datawrote < datalen )
      {
        plog( "Copy error (no space left on target?)\n" );
        goto done;
      }
      total += datalen;
      if( datalen < SHELL_COPY_BUFSIZE )
        break;
    }
  }
  plog( "done (%u bytes).\n", ( unsigned )total );
  res = 1;
done:
  if( fds != -1 )
    close( fds );
  if( fdd != -1 )
    close( fdd );
  if( buf )
    free( buf );
  return res;
}
开发者ID:mbraathen,项目名称:elua,代码行数:90,代码来源:shell.c

示例4: version_guess_from_hashcode

const char *  /* Original version by Solomon Peachy */
version_guess_from_hashcode(sci_version_t *result, int *res_version, guint32 *code)
{
	int i;
	int fd = -1;
	int left = VERSION_DETECT_HASH_SIZE;
	guint32 hash_code;
	guint8 buf[VERSION_DETECT_BUF_SIZE];

	if (IS_VALID_FD(fd = sci_open("resource.001", O_RDONLY|O_BINARY))) {
		hash_code = HASHCODE_MAGIC_RESOURCE_001;
	} else if (IS_VALID_FD(fd = sci_open("resource.000", O_RDONLY|O_BINARY))) {
		hash_code = HASHCODE_MAGIC_RESOURCE_000;
	} else {
		sciprintf("Warning: Could not find RESOURCE.000 or RESOURCE.001, cannot determine hash code\n");
		*code = 0;
		/* complete and utter failure */
		return NULL;
	}

	while (left > 0) {
		int len = read(fd, buf, left < VERSION_DETECT_BUF_SIZE ? left : VERSION_DETECT_BUF_SIZE);

		if (len == -1) {
			sciprintf("Warning: read error while computing hash code for resource file\n");
			*code = 0;
			return NULL;
		}

		if (len == 0)
			/* EOF */
			break;

		for (i = 0; i < len; i++)
			hash_code = (hash_code * 19) + *(buf + i);

		/* This is the string hashing algorithm used by Objective Caml 3.08; the general idea
		** of multiplying the previous hash code with a prime number between 5 and 23 appears
		** to be generally considered to be a "good" approach to exhausting the entire 32 bit
		** number space in a somewhat equal distribution. For large chunks of data, such as
		** SCI resource files, this should both perform well and yield a good distribution,
		** or at least that's what standard library designers have been assuming for quite a
		** while. */

		left -= len;
	}

	close(fd);

	*code = hash_code;

	for (i = 0 ; sci_games[i].name ; i++) {
		if (sci_games[i].id == hash_code) {
			*result = sci_games[i].version;
			*res_version = sci_games[i].res_version;
			return sci_games[i].name;
		}
	}

	return NULL; /* Failed to find matching game */
}
开发者ID:RangelReale,项目名称:freesci-pnd,代码行数:61,代码来源:versions.c

示例5: tailbyteoffset

void tailbyteoffset(int fd, char *fn, int isregfile, ssize_t len)
{
    ssize_t n, halfbuf;

    if (isregfile)   /* should be seekable, so we'll do so; it's fastest */
    {
        if (offset > 0)
            offset = (offset - 1) > len ? len : offset - 1;
        else
            offset = (len + offset) > 0 ? len + offset : 0;

        if (lseek(fd, (off_t)offset, SEEK_SET) == (off_t)-1)
            fatal(SYSERR, fn);

        copytoeof(fd, fn);
    }

    else   /* possibly non-seekable */
    {
        if (offset > 0)   /* forwards through file */
        {
            offset--;

            while(1)
            {
                if ((n = read(fd, buf, bufsize)) < 0)
                    fatal(SYSERR, fn);

                if (n == 0)
                    offset = 0;

                if (offset <= n)
                    break;
                else
                    offset -= n;
            }

            if (write(STDOUT_FILENO, buf + offset, n - offset) != n - offset)
                fatal(SYSERR, "stdout");

            copytoeof(fd, fn);
        }

        else   /* backwards through file; remember that offset is negative */
        {
            halfbuf = bufsize / 2;

            if ((n = read(fd, buf, bufsize)) < 0)
                fatal(SYSERR, fn);

            if (n < bufsize)   /* we've got the whole file */
            {
                offset = (n + offset) < 0 ? 0 : n + offset;
                len = n - offset;
            }

            else   /* we haven't got the whole file */
            {
                while(1)   /* page through the file, half a buffer at a time */
                {
                    memcpy(buf, buf + halfbuf, halfbuf);

                    if ((n = read(fd, buf + halfbuf, halfbuf)) < 0)
                        fatal(SYSERR, fn);
                    else if (n < halfbuf)
                        break;
                }

                offset = (halfbuf + n + offset) < 0 ? 0 : halfbuf + n + offset;
                len = halfbuf + n - offset;
            }

            if (write(STDOUT_FILENO, buf + offset, len) != len)
                fatal(SYSERR, "stdout");
        }
    }
}
开发者ID:mooseman,项目名称:pdcore,代码行数:77,代码来源:tail.c

示例6: adaptor_init

int adaptor_init(zhandle_t *zh)
{
    pthread_mutexattr_t recursive_mx_attr;
    struct adaptor_threads *adaptor_threads = calloc(1, sizeof(*adaptor_threads));
    if (!adaptor_threads) {
        LOG_ERROR(("Out of memory"));
        return -1;
    }

    /* We use a pipe for interrupting select() in unix/sol and socketpair in windows. */
#ifdef WIN32   
    if (create_socket_pair(adaptor_threads->self_pipe) == -1){
       LOG_ERROR(("Can't make a socket."));
#else
    if(pipe(adaptor_threads->self_pipe)==-1) {
        LOG_ERROR(("Can't make a pipe %d",errno));
#endif
        free(adaptor_threads);
        return -1;
    }
    set_nonblock(adaptor_threads->self_pipe[1]);
    set_nonblock(adaptor_threads->self_pipe[0]);

    pthread_mutex_init(&zh->auth_h.lock,0);

    zh->adaptor_priv = adaptor_threads;
    pthread_mutex_init(&zh->to_process.lock,0);
    pthread_mutex_init(&adaptor_threads->zh_lock,0);
    // to_send must be recursive mutex    
    pthread_mutexattr_init(&recursive_mx_attr);
    pthread_mutexattr_settype(&recursive_mx_attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(&zh->to_send.lock,&recursive_mx_attr);
    pthread_mutexattr_destroy(&recursive_mx_attr);
    
    pthread_mutex_init(&zh->sent_requests.lock,0);
    pthread_cond_init(&zh->sent_requests.cond,0);
    pthread_mutex_init(&zh->completions_to_process.lock,0);
    pthread_cond_init(&zh->completions_to_process.cond,0);
    start_threads(zh);
    return 0;
}

void adaptor_finish(zhandle_t *zh)
{
    struct adaptor_threads *adaptor_threads;
    // make sure zh doesn't get destroyed until after we're done here
    api_prolog(zh); 
    adaptor_threads = zh->adaptor_priv;
    if(adaptor_threads==0) {
        api_epilog(zh,0);
        return;
    }

    if(!pthread_equal(adaptor_threads->io,pthread_self())){
        wakeup_io_thread(zh);
        pthread_join(adaptor_threads->io, 0);
    }else
        pthread_detach(adaptor_threads->io);
    
    if(!pthread_equal(adaptor_threads->completion,pthread_self())){
        pthread_mutex_lock(&zh->completions_to_process.lock);
        pthread_cond_broadcast(&zh->completions_to_process.cond);
        pthread_mutex_unlock(&zh->completions_to_process.lock);
        pthread_join(adaptor_threads->completion, 0);
    }else
        pthread_detach(adaptor_threads->completion);
    
    api_epilog(zh,0);
}

void adaptor_destroy(zhandle_t *zh)
{
    struct adaptor_threads *adaptor = zh->adaptor_priv;
    if(adaptor==0) return;
    
    pthread_cond_destroy(&adaptor->cond);
    pthread_mutex_destroy(&adaptor->lock);
    pthread_mutex_destroy(&zh->to_process.lock);
    pthread_mutex_destroy(&zh->to_send.lock);
    pthread_mutex_destroy(&zh->sent_requests.lock);
    pthread_cond_destroy(&zh->sent_requests.cond);
    pthread_mutex_destroy(&zh->completions_to_process.lock);
    pthread_cond_destroy(&zh->completions_to_process.cond);
    pthread_mutex_destroy(&adaptor->zh_lock);

    pthread_mutex_destroy(&zh->auth_h.lock);

    close(adaptor->self_pipe[0]);
    close(adaptor->self_pipe[1]);
    free(adaptor);
    zh->adaptor_priv=0;
}

int wakeup_io_thread(zhandle_t *zh)
{
    struct adaptor_threads *adaptor_threads = zh->adaptor_priv;
    char c=0;
#ifndef WIN32
    return write(adaptor_threads->self_pipe[1],&c,1)==1? ZOK: ZSYSTEMERROR;    
#else
//.........这里部分代码省略.........
开发者ID:OpenPOWER-BigData,项目名称:HDP-zookeeper,代码行数:101,代码来源:mt_adaptor.c

示例7: read

char memfile::getc()
{
	char ch = 0;
	read(&ch, 1);
	return ch;
}
开发者ID:JianchengZh,项目名称:QPPHTTPServer,代码行数:6,代码来源:memfile.cpp

示例8: main

int main (int argc, char **argv)
{
	int fd = -1, err = 0, readbyte = 0, j;
	struct mtd_info_user mtdinfo;
	char buf[sizeof(image_header_t)];
	int found = 0;

	cmdname = *argv;

	while (--argc > 0 && **++argv == '-') {
		while (*++*argv) {
			switch (**argv) {
			case 'c':
				if (--argc <= 0)
					usage ();
				sectorcount = (unsigned int)atoi(*++argv);
				cflag = 1;
				goto NXTARG;
			case 'o':
				if (--argc <= 0)
					usage ();
				sectoroffset = (unsigned int)atoi(*++argv);
				goto NXTARG;

			case 's':
				if (--argc <= 0)
					usage ();
				sectorsize = (unsigned int)atoi(*++argv);
				sflag = 1;
				goto NXTARG;
			default:
				usage ();
			}
		}
NXTARG:		;
	}

	if (argc != 1 || cflag == 0 || sflag == 0)
		usage();

	devicefile = *argv;

	fd = open(devicefile, O_RDONLY);
	if (fd < 0) {
		fprintf (stderr, "%s: Can't open %s: %s\n",
			 cmdname, devicefile, strerror(errno));
		exit(EXIT_FAILURE);
	}

	err = ioctl(fd, MEMGETINFO, &mtdinfo);
	if (err < 0) {
		fprintf(stderr, "%s: Cannot get MTD information: %s\n",cmdname,
			strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (mtdinfo.type != MTD_NORFLASH && mtdinfo.type != MTD_NANDFLASH) {
		fprintf(stderr, "%s: Unsupported flash type %u\n",
			cmdname, mtdinfo.type);
		exit(EXIT_FAILURE);
	}

	if (sectorsize * sectorcount != mtdinfo.size) {
		fprintf(stderr, "%s: Partition size (%d) incompatible with "
			"sector size and count\n", cmdname, mtdinfo.size);
		exit(EXIT_FAILURE);
	}

	if (sectorsize * sectoroffset >= mtdinfo.size) {
		fprintf(stderr, "%s: Partition size (%d) incompatible with "
			"sector offset given\n", cmdname, mtdinfo.size);
		exit(EXIT_FAILURE);
	}

	if (sectoroffset > sectorcount - 1) {
		fprintf(stderr, "%s: Sector offset cannot be grater than "
			"sector count minus one\n", cmdname);
		exit(EXIT_FAILURE);
	}

	printf("Searching....\n");

	for (j = sectoroffset; j < sectorcount; ++j) {

		if (lseek(fd, j*sectorsize, SEEK_SET) != j*sectorsize) {
			fprintf(stderr, "%s: lseek failure: %s\n",
			cmdname, strerror(errno));
			exit(EXIT_FAILURE);
		}

		err = flash_bad_block(fd, mtdinfo.type, j*sectorsize);
		if (err < 0)
			exit(EXIT_FAILURE);
		if (err)
			continue; /* Skip and jump to next */

		readbyte = read(fd, buf, sizeof(image_header_t));
		if (readbyte != sizeof(image_header_t)) {
			fprintf(stderr, "%s: Can't read from device: %s\n",
			cmdname, strerror(errno));
//.........这里部分代码省略.........
开发者ID:Medvedroid,项目名称:OT_903D-kernel-2.6.35.7,代码行数:101,代码来源:imls.c

示例9: cmp

int cmp( int fh[2], char *names[2], long offs[2] ) {

    int         i;
    const char  *fmt;
    int         bytes_read[2];
    size_t      amt;

    for(;;) {
        bytes_read[0] = read( fh[0], &buffer[0][0], BUFFER_SIZE );
        if( bytes_read[0] == -1 ) {
            Die( "error reading %s: %s\n", names[0], strerror( errno ) );
        }
        bytes_read[1] = read( fh[1], &buffer[1][0], BUFFER_SIZE );
        if( bytes_read[1] == -1 ) {
            Die( "error reading %s: %s\n", names[1], strerror( errno ) );
        }
        amt = bytes_read[0] < bytes_read[1] ? bytes_read[0] : bytes_read[1];
        if( memcmp( &buffer[0][0], &buffer[1][0], amt ) ) {
            for( i = 0; i < amt; ++i ) {
                if( buffer[0][i] != buffer[1][i] ) {
                    if( !flagSayNothing ) {
                        if( offs[0] == offs[1] ) {
                            if( flagSayItInHex ) {
                                fmt = "offset %08lx: %s=%02x, %s=%02x\n";
                            } else {
                                fmt = "offset %lu: %s=%u, %s=%u\n";
                            }
                            printf( fmt, offs[0]+i, names[0], buffer[0][i],
                                                    names[1], buffer[1][i] );
                        } else {
                            if( flagSayItInHex ) {
                                fmt = "offset %08lx %s=%02x, offset %08lx %s=%02x\n";
                            } else {
                                fmt = "offset %lu %s=%u, offset %lu %s=%u\n";
                            }
                            printf( fmt, offs[0]+i, names[0], buffer[0][i],
                                         offs[1]+i, names[1], buffer[1][i] );
                        }
                    }
                    if( !flagKeepGoing ) return( 1 );
                }
            }
        }
        offs[0] += bytes_read[0];
        offs[1] += bytes_read[1];
        if( bytes_read[0] != bytes_read[1] ) {
            if( !flagSayNothing ) {
                if( flagSayItInHex ) {
                    fmt = "%s ends prematurely at offset %08lx\n";
                } else {
                    fmt = "%s ends prematurely at offset %u\n";
                }
                if( bytes_read[0] < bytes_read[1] ) {
                    printf( fmt, names[0], offs[0] );
                } else {
                    printf( fmt, names[1], offs[1] );
                }
            }
            return( 1 );
        }
        if( bytes_read[0] == 0 ) break;
    }
    return( 0 );
}
开发者ID:ABratovic,项目名称:open-watcom-v2,代码行数:64,代码来源:cmp.c

示例10: md0Ramdisk

// Notify OS X that a ramdisk has been setup. XNU with attach this to /dev/md0
void md0Ramdisk()
{
	RAMDiskParam ramdiskPtr;
	char filename[512];
	const char* override_filename = 0;
	int fh = -1;
	int len;
	
	if(getValueForKey(kMD0Image, &override_filename, &len,  
				   &bootInfo->chameleonConfig))
	{
		// Use user specified md0 file
		strncpy(filename, override_filename, sizeof(filename) );
		fh = open(filename, 0);
		
		if(fh < 0)
		{
			snprintf(filename, sizeof(filename), "rd(0,0)/Extra/%s", override_filename);
			fh = open(filename, 0);

			if(fh < 0)
			{
				snprintf(filename, sizeof(filename), "/Extra/%s", override_filename);
				fh = open(filename, 0);
			}
		}		
	}

	if(fh < 0)
	{
		strcpy(filename, "rd(0,0)/Extra/Postboot.img");
		fh = open(filename, 0);

		if(fh < 0)
		{
			strcpy(filename, "/Extra/Postboot.img");	// Check /Extra if not in rd(0,0)
			fh = open(filename, 0);
		}
	}		

	if (fh >= 0)
	{
		verbose("Enabling ramdisk %s\n", filename);

		ramdiskPtr.size  = file_size(fh);
		ramdiskPtr.base = AllocateKernelMemory(ramdiskPtr.size);

		if(ramdiskPtr.size && ramdiskPtr.base)
		{
			// Read new ramdisk image contents in kernel memory.
			if (read(fh, (char*) ramdiskPtr.base, ramdiskPtr.size) == ramdiskPtr.size)
			{
				AllocateMemoryRange("RAMDisk", ramdiskPtr.base, ramdiskPtr.size, kBootDriverTypeInvalid);
				Node* node = DT__FindNode("/chosen/memory-map", false);
				if(node != NULL)
				{
					DT__AddProperty(node, "RAMDisk", sizeof(RAMDiskParam),  (void*)&ramdiskPtr);		
				}
				else
				{
					verbose("Unable to notify Mac OS X of the ramdisk %s.\n", filename);
				}
			}
			else
			{
				verbose("Unable to read md0 image %s.\n", filename);
			}			
		}
		else
		{
			verbose("md0 image %s is empty.\n", filename);
		}

		close(fh);

	}
}
开发者ID:Klozz,项目名称:ChameleonFRK,代码行数:78,代码来源:ramdisk.c

示例11: munge_line_in_editor

static int
munge_line_in_editor(int count, int key)
{
  int line_number = 0, column_number = 0,  ret, tmpfile_fd, bytes_read;
  size_t tmpfilesize;
  char *p, *tmpfilename, *text_to_edit;
  char *editor_command1, *editor_command2, *editor_command3, *editor_command4,
    *line_number_as_string, *column_number_as_string;
  char *input, *rewritten_input, *rewritten_input2,  **possible_editor_commands;


  if (!multiline_separator)
    return 0;

  tmpfile_fd = open_unique_tempfile(multi_line_tmpfile_ext, &tmpfilename);

  text_to_edit =
    search_and_replace(multiline_separator, "\n", rl_line_buffer, rl_point,
                       &line_number, &column_number);
  write_patiently(tmpfile_fd, text_to_edit, strlen(text_to_edit), "to temporary file");

  if (close(tmpfile_fd) != 0) /* improbable */
    myerror("couldn't close temporary file %s", tmpfilename); 

  /* find out which editor command we have to use */
  possible_editor_commands = list4(getenv("RLWRAP_EDITOR"), getenv("EDITOR"), getenv("VISUAL"), "vi +%L");
  editor_command1 = first_of(possible_editor_commands);
  line_number_as_string = as_string(line_number);
  column_number_as_string = as_string(column_number);
  editor_command2 =
    search_and_replace("%L", line_number_as_string, editor_command1, 0, NULL,
                       NULL);
  editor_command3 =
    search_and_replace("%C", column_number_as_string, editor_command2, 0,
                       NULL, NULL);
  editor_command4 = add3strings(editor_command3, " ", tmpfilename);
  

  /* call editor, temporarily restoring terminal settings */    
  if (terminal_settings_saved && (tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_terminal_settings) < 0))    /* reset terminal */
    myerror("tcsetattr error on stdin");
  DPRINTF1(DEBUG_READLINE, "calling %s", editor_command4);
  if ((ret = system(editor_command4))) {
    if (WIFSIGNALED(ret)) {
      fprintf(stderr, "\n"); errno = 0;
      myerror("editor killed by signal");
    } else {    
      myerror("failed to invoke editor with '%s'", editor_command4);
    }
  }
  completely_mirror_slaves_terminal_settings();
  ignore_queued_input = TRUE;  

  /* read back edited input, replacing real newline with substitute */
  tmpfile_fd = open(tmpfilename, O_RDONLY);
  if (tmpfile_fd < 0)
    myerror("could not read temp file %s", tmpfilename);
  tmpfilesize = filesize(tmpfilename);
  input = mymalloc(tmpfilesize + 1);
  bytes_read = read(tmpfile_fd, input, tmpfilesize);
  if (bytes_read < 0)
    myerror("unreadable temp file %s", tmpfilename);
  input[bytes_read] = '\0';
  rewritten_input = search_and_replace("\t", "    ", input, 0, NULL, NULL);     /* rlwrap cannot handle tabs in input lines */
  rewritten_input2 =
    search_and_replace("\n", multiline_separator, rewritten_input, 0, NULL,
                       NULL);
  for(p = rewritten_input2; *p ;p++)
    if(*p >= 0 && *p < ' ') /* @@@FIXME: works for UTF8, but not UTF16 or UTF32 (Mention this in manpage?)*/ 
      *p = ' ';        /* replace all control characters (like \r) by spaces */


  rl_delete_text(0, strlen(rl_line_buffer));
  rl_point = 0;  
  clear_line();
  cr();
  my_putstr(saved_rl_state.cooked_prompt);
  rl_insert_text(rewritten_input2);
  rl_point = 0;                 /* leave cursor on predictable place */
  rl_done = 1;                  /* accept line immediately */

  


  /* wash those dishes */
  if (unlink(tmpfilename))
    myerror("could not delete temporary file %s", tmpfilename);
  free(editor_command2);
  free(editor_command3);
  free(editor_command4);
  free(line_number_as_string);
  free(column_number_as_string);
  free(tmpfilename);
  free(text_to_edit);
  free(input);
  free(rewritten_input);
  free(rewritten_input2);
  
  return_key = (char)'\n';
  return 0;
//.........这里部分代码省略.........
开发者ID:jsarenik,项目名称:rlwrap,代码行数:101,代码来源:readline.c

示例12: mountRAMDisk

int mountRAMDisk(const char * param)
{
	int fh = 0, ramDiskSize;
	int error = 0;

	// Get file handle for ramdisk file.
	fh = open(param, 0);
	if (fh != -1)
	{
		printf("\nreading ramdisk image: %s", param);

		ramDiskSize = file_size(fh);
		if (ramDiskSize > 0)
		{
			// Unmount previously mounted image if exists.
			umountRAMDisk();

			// Read new ramdisk image contents into PREBOOT_DATA area.
			if (read(fh, (char *)PREBOOT_DATA, ramDiskSize) != ramDiskSize) error = -1;
		}
		else error = -1;

		close(fh);
	}
	else error = -1;

	if (error == 0)
	{
		// Save filename in gRAMDiskFile to display information.
		strlcpy(gRAMDiskFile, param, sizeof(gRAMDiskFile));

		// Set gMI as well for the multiboot ramdisk driver hook.
		gMI = gRAMDiskMI = malloc(sizeof(multiboot_info));
		struct multiboot_module * ramdisk_module = malloc(sizeof(multiboot_module));

		// Fill in multiboot info and module structures.
		if (gRAMDiskMI != NULL && ramdisk_module != NULL)
		{
			gRAMDiskMI->mi_mods_count = 1;
			gRAMDiskMI->mi_mods_addr = (uint32_t)ramdisk_module;
			ramdisk_module->mm_mod_start = PREBOOT_DATA;
			ramdisk_module->mm_mod_end = PREBOOT_DATA + ramDiskSize;

			// Set ramdisk driver hooks.
			p_get_ramdisk_info = &multiboot_get_ramdisk_info;
			p_ramdiskReadBytes = &multibootRamdiskReadBytes;

			int partCount; // unused
			// Save bvr of the mounted image.
			gRAMDiskVolume = diskScanBootVolumes(0x100, &partCount);
			if(gRAMDiskVolume == NULL)
			{
				umountRAMDisk();
				printf("\nRamdisk contains no partitions.");
			}
			else
			{
				char dirSpec[128];

				// Reading ramdisk configuration.
				strlcpy(dirSpec, RAMDISKCONFIG_FILENAME, sizeof(dirSpec));

				if (loadConfigFile(dirSpec, &bootInfo->ramdiskConfig) == 0)
				{
					getBoolForKey("BTAlias", &gRAMDiskBTAliased, &bootInfo->ramdiskConfig);
				}
				else
				{
					printf("\nno ramdisk config...\n");
				}

				printf("\nmounting: done");
			}
		}
	}

	return error;
}
开发者ID:Klozz,项目名称:ChameleonFRK,代码行数:78,代码来源:ramdisk.c

示例13: udev_read_event

void
udev_read_event(int fd)
{
	struct pdev_array_entry	*pae;
	prop_dictionary_t	dict, evdict, devdict;
	prop_number_t		pn;
	prop_string_t		ps;
	prop_object_t		po;
	prop_array_t		pa;
	char	*xml;
	int	n, idx, evtype;
	size_t	sz;

	sz = 4096 * 1024;

	xml = malloc(sz); /* 4 MB */
again:
	if ((n = read(fd, xml, sz)) <= 0) {
		if (errno == ENOMEM) {
			sz <<= 2;
			if ((xml = realloc(xml, sz)) == NULL) {
				syslog(LOG_ERR, "could not realloc xml memory");
				return;
			}
			goto again;
		}
		free(xml);
		return;
	}

	dict = prop_dictionary_internalize(xml);
	free(xml);
	if (dict == NULL) {
		syslog(LOG_ERR, "internalization of xml failed");
		return;
	}

	pn = prop_dictionary_get(dict, "evtype");
	if (pn == NULL) {
		syslog(LOG_ERR, "read_event: no key evtype");
		goto out;
	}

	evtype = prop_number_integer_value(pn);

	evdict = prop_dictionary_get(dict, "evdict");
	if (evdict == NULL) {
		syslog(LOG_ERR, "read_event: no key evdict");
		goto out;
	}

	switch (evtype) {
	case UDEV_EVENT_ATTACH:
		monitor_queue_event(dict);
		pae = pdev_array_entry_get_last();
		pa = prop_array_copy(pae->pdev_array);
		pdev_array_entry_unref(pae);
		if (pa == NULL)
			goto out;
		prop_array_add(pa, evdict);
		pdev_array_entry_insert(pa);
		break;

	case UDEV_EVENT_DETACH:
		monitor_queue_event(dict);
		if ((devdict = find_dev_dict(-1, evdict, &idx)) == NULL)
			goto out;
		pae = pdev_array_entry_get_last();
		pa = prop_array_copy(pae->pdev_array);
		pdev_array_entry_unref(pae);
		if (pa == NULL)
			goto out;
		prop_array_remove(pa, idx);
		pdev_array_entry_insert(pa);
		break;

	case UDEV_EV_KEY_UPDATE:
		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)
			goto out;
		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)
			goto out;
		if ((po = prop_dictionary_get(evdict, "value")) == NULL)
			goto out;
		/* prop_object_retain(po); */ /* not necessary afaik */
		prop_dictionary_set(devdict, prop_string_cstring_nocopy(ps), po);
		break;

	case UDEV_EV_KEY_REMOVE:
		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)
			goto out;
		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)
			goto out;
		prop_dictionary_remove(devdict, prop_string_cstring_nocopy(ps));
		break;

	default:
		syslog(LOG_ERR, "read_event: unknown evtype %d", evtype);
	}

out:
//.........这里部分代码省略.........
开发者ID:alexandermerritt,项目名称:dragonfly,代码行数:101,代码来源:udevd.c

示例14: main

int
main(int argc, char **argv)
{
    const char *progname = argv[0];
    struct ccn *ccn = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_charbuf *pname = NULL;
    struct ccn_charbuf *temp = NULL;
    struct ccn_charbuf *extopt = NULL;
    long expire = -1;
    int versioned = 0;
    size_t blocksize = 8*1024;
    int status = 0;
    int res;
    ssize_t read_res;
    unsigned char *buf = NULL;
    enum ccn_content_type content_type = CCN_CONTENT_DATA;
    struct ccn_closure in_interest = {.p=&incoming_interest};
    const char *postver = NULL;
    const char *key_uri = NULL;
    int force = 0;
    int verbose = 0;
    int timeout = -1;
    int setfinal = 0;
    int prefixcomps = -1;
    int fd;
    struct ccn_signing_params sp = CCN_SIGNING_PARAMS_INIT;
    
    while ((res = getopt(argc, argv, "e:fhk:lvV:p:t:w:x:")) != -1) {
        switch (res) {
            case 'e':
                if (extopt == NULL)
                    extopt = ccn_charbuf_create();
                fd = open(optarg, O_RDONLY);
                if (fd < 0) {
                    perror(optarg);
                    exit(1);
                }
                for (;;) {
                    read_res = read(fd, ccn_charbuf_reserve(extopt, 64), 64);
                    if (read_res <= 0)
                        break;
                    extopt->length += read_res;
                }
                if (read_res < 0)
                    perror(optarg);
                close(fd);
                break;
            case 'f':
                force = 1;
                break;
            case 'l':
                setfinal = 1; // set FinalBlockID to last comp of name
                break;
            case 'k':
                key_uri = optarg;
                break;
            case 'p':
                prefixcomps = atoi(optarg);
                if (prefixcomps < 0)
                    usage(progname);
                break;
            case 'x':
                expire = atol(optarg);
                if (expire <= 0)
                    usage(progname);
                break;
            case 'v':
                verbose = 1;
                break;
            case 'V':
                versioned = 1;
                postver = optarg;
                if (0 == memcmp(postver, "%00", 3))
                    setfinal = 1;
                break;
            case 'w':
                timeout = atol(optarg);
                if (timeout <= 0)
                    usage(progname);
                timeout *= 1000;
                break;
            case 't':
                if (0 == strcasecmp(optarg, "DATA")) {
                    content_type = CCN_CONTENT_DATA;
                    break;
                }
                if (0 == strcasecmp(optarg, "ENCR")) {
                    content_type = CCN_CONTENT_ENCR;
                    break;
                }
                if (0 == strcasecmp(optarg, "GONE")) {
                    content_type = CCN_CONTENT_GONE;
                    break;
                }
                if (0 == strcasecmp(optarg, "KEY")) {
                    content_type = CCN_CONTENT_KEY;
                    break;
                }
                if (0 == strcasecmp(optarg, "LINK")) {
//.........这里部分代码省略.........
开发者ID:IthacaDream,项目名称:ccnx,代码行数:101,代码来源:ccnpoke.c

示例15: updateStats

void updateStats(void *)
{
    char pLogBuffer[1024];
    static int log_len;
    static struct timeval last_time;
    static long last_rx=0; static long last_tx=0;  static long connect_time=0;
    char *ptr; int fd; char buf[1024];
    long rx = -1; long tx = -1;
    float spi = 0.0; float spo = 0.0;
    static bool modleds = false;
    int len = -1;

    fd = open("/proc/net/dev", O_RDONLY);
    if(fd > 0) {

        len = read(fd, buf, 1023);
        close(fd);

        if(len>0) {
            buf[len] = '\0';
            ptr = strstr( buf, "ppp0" );
        }
    }

    if(fd==-1 || len < 0 || ptr == NULL)
    {
        if (modleds) {
            dock->remove_from_tray(mModemLeds);
            modleds = false;
        }
        last_rx=0; last_tx=0; connect_time=0;

    }
    else
    {
        long dt; int ct; struct timeval tv;

        gettimeofday(&tv, NULL);
	     dt = (tv.tv_sec - last_time.tv_sec) * 1000;
	     dt += (tv.tv_usec - last_time.tv_usec) / 1000;

	     if (dt > 0) {
	     sscanf(ptr, "%*[^:]:%ld %*d %*d %*d %*d %*d %*d %*d %ld", &rx, &tx); 
	     spi = (rx - last_rx) / dt;
	     spi = spi / 1024.0 * 1000.0;
	     spo = (tx - last_tx) / dt;
	     spo = spo / 1024.0 * 1000.0;
		

	     if ( connect_time == 0 ) 
	         connect_time = tv.tv_sec;
	     ct = (int)(tv.tv_sec - connect_time);

	     snprintf(pLogBuffer, 1024,
			     _("Received: %ld kB (%.1f kB/s)\n"
			     "Sent:     %ld kB (%.1f  kB/s)\n"
			     "Duration: %d min %d sec"), 
			      rx / 1024, spi, tx / 1024, spo, ct / 60, ct % 60 );
	     last_rx = rx;
	     last_tx = tx;
	     last_time.tv_sec = tv.tv_sec;
	     last_time.tv_usec = tv.tv_usec;

	     log_len = 0;

	     if ((int)(spi) > 0) 
	     {
	         mLedIn->color( (Fl_Color)2 );
	         mLedIn->redraw();
	     }    
	     else 
	     {
	         mLedIn->color( (Fl_Color)968701184 );
	         mLedIn->redraw();
	     }

	     if ( (int)(spo) > 0 ) {
	         mLedOut->color( (Fl_Color)2 );
	         mLedOut->redraw();
	     } else {
	         mLedOut->color( (Fl_Color)968701184 );
	         mLedOut->redraw();
		}
        mModemLeds->tooltip(pLogBuffer);
	}
        if (!modleds) 
	     {
	         dock->add_to_tray(mModemLeds);
	         modleds = true;
	     }    
    }    

    updateSetup();
    Fl::repeat_timeout(1.0f, updateStats);
}
开发者ID:edeproject,项目名称:svn,代码行数:95,代码来源:workpanel.cpp


注:本文中的read函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。