Esempio n. 1
0
void limpiarbuffer(void)
{
    int ch;
    while( (ch = fgetc(stdin)) != EOF && ch != '\n' ){}
}
Esempio n. 2
0
int getfileline(void *vp, char *linebuf, int linebuf_size)
{
	/* Static buffers we will return. */
	FILE *fp = (FILE *)vp;
	unsigned char   c;
	unsigned char  *p;
	size_t linebuf_len;

	if (fp == NULL) {
		DEBUG(0,("getfileline: Bad file pointer.\n"));
		return -1;
	}

	/*
	 * Scan the file, a line at a time.
	 */
	while (!feof(fp)) {
		linebuf[0] = '\0';

		fgets(linebuf, linebuf_size, fp);
		if (ferror(fp)) {
			return -1;
		}

		/*
		 * Check if the string is terminated with a newline - if not
		 * then we must keep reading and discard until we get one.
		 */

		linebuf_len = strlen(linebuf);
		if (linebuf_len == 0) {
			linebuf[0] = '\0';
			return 0;
		}

		if (linebuf[linebuf_len - 1] != '\n') {
			c = '\0';
			while (!ferror(fp) && !feof(fp)) {
				c = fgetc(fp);
				if (c == '\n') {
					break;
				}
			}
		} else {
			linebuf[linebuf_len - 1] = '\0';
		}

#ifdef DEBUG_PASSWORD
		DEBUG(100, ("getfileline: got line |%s|\n", linebuf));
#endif
		if ((linebuf[0] == 0) && feof(fp)) {
			DEBUG(4, ("getfileline: end of file reached\n"));
			return 0;
		}

		if (linebuf[0] == '#' || linebuf[0] == '\0') {
			DEBUG(6, ("getfileline: skipping comment or blank line\n"));
			continue;
		}

		p = (unsigned char *) strchr_m(linebuf, ':');
		if (p == NULL) {
			DEBUG(0, ("getfileline: malformed line entry (no :)\n"));
			continue;
		}
		return linebuf_len;
	}
	return -1;
}
int main(int argc, char **argv) {

	openlog("redirect_rewrite", LOG_PID|LOG_CONS, LOG_USER);

	compile_patterns();
	/* Allocate some memory */
	content = (char*) malloc(sizeof(char) * BUF_SIZE);
	memset (content,0,sizeof(char) * BUF_SIZE);
	/* Check if the memory couldn't be allocated; if it's the case, handle the problem as appropriate. */
	if (NULL == content) {
#ifdef DEBUG
		perror("Could not allocate memory");
#endif
		return EXIT_FAILURE;
	}
	unsigned int n = 0;
	unsigned int localAllocatedSize, oldSize;
	localAllocatedSize = allocatedSize;

	memset (content,0,sizeof(char) * localAllocatedSize);
	int c;
	while((c = fgetc(stdin)) != EOF){

		if(n==localAllocatedSize){
			oldSize = localAllocatedSize;
			localAllocatedSize += INCR_SIZE;
			allocatedSize = localAllocatedSize;
			content = (char*) realloc(content, sizeof(char) * localAllocatedSize);
			if (NULL == content) {
				perror("Could not allocate memory");
				exit(1);
			}
			if(oldSize<localAllocatedSize)
				memset (content+oldSize,0,sizeof(char) * INCR_SIZE);
		}

		/* Read line into contents */
		if (c != '\n'){
			content[n] = c;
			n++;
			continue;
		}
		n=0;

		//printf("[X]Content %s \n\n", content);

		/* Grab the text up to the space character */
		char* channel = strtok (content, " ");

		char* url;
		if(channel != NULL){
			url = match(channel);

			/* Grab more text up to the next space character
			 * and try to get a redirect url match */
			char* original_url;
			if(NULL == url){
				original_url = strtok (NULL, " ");
				if(NULL != original_url){
					url = match(original_url);
				}
				printf("%s ", channel);
			}
			if(NULL == url){
				printf("\n");
				fflush(stdout);
			}else{

				if(NULL != url){
					char buffer[2048];
					printf("302:%s\n", url);
					fflush(stdout);
					sprintf (buffer, "Redirecting: %s", url);
					syslog(LOG_INFO, buffer);
				}else{
					printf("\n");
					fflush(stdout);
				}
			}

		}else{
			syslog(LOG_INFO, "No url found");
		}
		memset (content,0,sizeof(char) * localAllocatedSize);
	}
	closelog();
	return EXIT_SUCCESS;
}
Esempio n. 4
0
int main(int argc, char* argv[])
{
    // check for correct number of args
    if (argc != 2 && argc != 3)
    {
        printf("Usage: speller [dictionary] text\n");
        return 1;
    }

    // structs for timing data
    struct rusage before, after;

    // benchmarks
    double ti_load = 0.0, ti_check = 0.0, ti_size = 0.0, ti_unload = 0.0;

    // determine dictionary to use
    char* dictionary = (argc == 3) ? argv[1] : DICTIONARY;

    // load dictionary
    getrusage(RUSAGE_SELF, &before);
    bool loaded = load(dictionary);
    getrusage(RUSAGE_SELF, &after);

    // abort if dictionary not loaded
    if (!loaded)
    {
        printf("Could not load %s.\n", dictionary);
        return 1;
    }

    // calculate time to load dictionary
    ti_load = calculate(&before, &after);

    // try to open text
    char* text = (argc == 3) ? argv[2] : argv[1];
    FILE* fp = fopen(text, "r");
    if (fp == NULL)
    {
        printf("Could not open %s.\n", text);
        unload();
        return 1;
    }

    // prepare to report misspellings
    printf("\nMISSPELLED WORDS\n\n");

    // prepare to spell-check
    int index = 0, misspellings = 0, words = 0;
    char word[LENGTH+1];

    // spell-check each word in text
    for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
    {
        // allow only alphabetical characters and apostrophes
        if (isalpha(c) || (c == '\'' && index > 0))
        {
            // append character to word
            word[index] = c;
            index++;

            // ignore alphabetical strings too long to be words
            if (index > LENGTH)
            {
                // consume remainder of alphabetical string
                while ((c = fgetc(fp)) != EOF && isalpha(c));

                // prepare for new word
                index = 0;
            }
        }

        // ignore words with numbers (like MS Word can)
        else if (isdigit(c))
        {
            // consume remainder of alphanumeric string
            while ((c = fgetc(fp)) != EOF && isalnum(c));

            // prepare for new word
            index = 0;
        }

        // we must have found a whole word
        else if (index > 0)
        {
            // terminate current word
            word[index] = '\0';

            // update counter
            words++;

            // check word's spelling
            getrusage(RUSAGE_SELF, &before);
            bool misspelled = !check(word);
            getrusage(RUSAGE_SELF, &after);

            // update benchmark
            ti_check += calculate(&before, &after);

            // print word if misspelled
            if (misspelled)
            {
                printf("%s\n", word);
                misspellings++;
            }

            // prepare for next word
            index = 0;
        }
    }

    // check whether there was an error
    if (ferror(fp))
    {
        fclose(fp);
        printf("Error reading %s.\n", text);
        unload();
        return 1;
    }

    // close text
    fclose(fp);

    // determine dictionary's size
    getrusage(RUSAGE_SELF, &before);
    unsigned int n = size();
    getrusage(RUSAGE_SELF, &after);

    // calculate time to determine dictionary's size
    ti_size = calculate(&before, &after);

    // unload dictionary
    getrusage(RUSAGE_SELF, &before);
    bool unloaded = unload();
    getrusage(RUSAGE_SELF, &after);

    // abort if dictionary not unloaded
    if (!unloaded)
    {
        printf("Could not unload %s.\n", dictionary);
        return 1;
    }

    // calculate time to unload dictionary
    ti_unload = calculate(&before, &after);

    // report benchmarks
    printf("\nWORDS MISSPELLED:     %d\n", misspellings);
    printf("WORDS IN DICTIONARY:  %d\n", n);
    printf("WORDS IN TEXT:        %d\n", words);
    printf("TIME IN load:         %.2f\n", ti_load);
    printf("TIME IN check:        %.2f\n", ti_check);
    printf("TIME IN size:         %.2f\n", ti_size);
    printf("TIME IN unload:       %.2f\n", ti_unload);
    printf("TIME IN TOTAL:        %.2f\n\n", 
     ti_load + ti_check + ti_size + ti_unload);

    // that's all folks
    return 0;
}
Esempio n. 5
0
char *get_file_contents (const char *filename) {
#ifdef USE_MEMORY_MAPPED_FILES
	HANDLE hFile = CreateFile(
		filename,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		return NULL;
	}

	HANDLE hMapFile = CreateFileMapping(
		hFile,
		NULL,
		PAGE_READONLY,
		0L,
		0L,
		NULL);

	LPBYTE lpData = (LPBYTE) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
	return (char *) lpData;
#else
	FILE *file;
	char *buffer;
	size_t size, read_size;

	// first try to open it
	file = fopen (filename, "rb");

	if (!file)
		return NULL;

	// find file size (Spencer says it's not a hack)
	fseek (file, 0, SEEK_END);
	size = ftell (file);
	rewind (file);


	// If there is a UTF-8 endian marker at the beginning of the file, skip it.
	const unsigned char utf8_endian_mark[] = {0xEF, 0xBB, 0xBF};
	bool matched = true;
	for (unsigned i = 0; matched && i < sizeof(utf8_endian_mark); i++) {
		int c = fgetc(file);
		if (c == EOF) {
			return NULL;
		}
		matched &= (unsigned char)c == utf8_endian_mark[i];
	}
	if (matched) {
		size -= sizeof(utf8_endian_mark);
	} else {
		rewind(file);
	}

	// now allocate the memory and read in the contents
	buffer = (char *) malloc (size + 1);
	read_size = fread (buffer, 1, size, file);
	fclose (file);

	if (read_size != size) {
		free (buffer);
		return NULL;
	}

	buffer[size] = '\0';
	return buffer;
#endif
}
Esempio n. 6
0
static int tvfscanf(FILE* stream, const char *format, va_list ap) {
  const char *p = format;
  char ch;
  int q = 0;
  uintmax_t val = 0;
  int rank = RANK_INT;    // Default rank
  unsigned int width = UINT_MAX;
  int base;
  int flags = 0;
  enum {
    ST_NORMAL,        // Ground state
    ST_FLAGS,         // Special flags
    ST_WIDTH,         // Field width
    ST_MODIFIERS,     // Length or conversion modifiers
    ST_MATCH_INIT,    // Initial state of %[ sequence
    ST_MATCH,         // Main state of %[ sequence
    ST_MATCH_RANGE,   // After - in a %[ sequence
  } state = ST_NORMAL;
  char *sarg = NULL;    // %s %c or %[ string argument
  enum Bail bail = BAIL_NONE;
  int converted = 0;    // Successful conversions
  unsigned long matchmap[((1 << CHAR_BIT)+(CHAR_BIT * sizeof(long) - 1)) /
      (CHAR_BIT * sizeof(long))];
  int matchinv = 0;   // Is match map inverted?
  unsigned char range_start = 0;
  off_t start_off = ftell(stream);

  // Skip leading spaces
  SkipSpace(stream);

  while ((ch = *p++) && !bail) {
    switch (state) {
      case ST_NORMAL:
        if (ch == '%') {
          state = ST_FLAGS;
          flags = 0; rank = RANK_INT; width = UINT_MAX;
        } else if (isspace(static_cast<unsigned char>(ch))) {
          SkipSpace(stream);
        } else {
          if (fgetc(stream) != ch)
            bail = BAIL_ERR;  // Match failure
        }
        break;

      case ST_FLAGS:
        if (ch == '*') {
          flags |= FL_SPLAT;
        } else if ('0' <= ch && ch <= '9') {
          width = (ch-'0');
          state = ST_WIDTH;
          flags |= FL_WIDTH;
        } else {
          state = ST_MODIFIERS;
          p--;      // Process this character again
        }
      break;

      case ST_WIDTH:
        if (ch >= '0' && ch <= '9') {
          width = width*10+(ch-'0');
        } else {
          state = ST_MODIFIERS;
          p--;      // Process this character again
        }
      break;

      case ST_MODIFIERS:
        switch (ch) {
          // Length modifiers - nonterminal sequences
          case 'h':
            rank--;     // Shorter rank
          break;
          case 'l':
            rank++;     // Longer rank
          break;
          case 'j':
            rank = kIntMaxRank;
          break;
          case 'z':
            rank = kSizeTRank;
          break;
          case 't':
            rank = kPtrDiffRank;
          break;
          case 'L':
          case 'q':
            rank = RANK_LONGLONG; // long double/long long
          break;

          default:
            // Output modifiers - terminal sequences
            state = ST_NORMAL;  // Next state will be normal
            if (rank < kMinRank)  // Canonicalize rank
              rank = kMinRank;
            else if (rank > kMaxRank)
              rank = kMaxRank;

          switch (ch) {
            case 'P':   // Upper case pointer
            case 'p':   // Pointer
              rank = RANK_PTR;
              base = 0;
            goto scan_int;

            case 'i':   // Base-independent integer
              base = 0;
            goto scan_int;

            case 'd':   // Decimal integer
              base = 10;
            goto scan_int;

            case 'o':   // Octal integer
              base = 8;
            goto scan_int;

            case 'u':   // Unsigned decimal integer
              base = 10;
            goto scan_int;

            case 'x':   // Hexadecimal integer
            case 'X':
              base = 16;
            goto scan_int;

            case 'n':   // Number of characters consumed
              val = ftell(stream) - start_off;
            goto set_integer;

            scan_int:
              q = SkipSpace(stream);
              if ( q <= 0 ) {
                bail = BAIL_EOF;
                break;
              }
              val = streamtoumax(stream, base);
              // fall through

            set_integer:
              if (!(flags & FL_SPLAT)) {
                converted++;
                switch(rank) {
                  case RANK_CHAR:
                    *va_arg(ap, unsigned char *)
                      = static_cast<unsigned char>(val);
                  break;
                  case RANK_SHORT:
                    *va_arg(ap, unsigned short *)
                      = static_cast<unsigned short>(val);
                  break;
                  case RANK_INT:
                    *va_arg(ap, unsigned int *)
                      = static_cast<unsigned int>(val);
                  break;
                  case RANK_LONG:
                    *va_arg(ap, unsigned long *)
                      = static_cast<unsigned long>(val);
                  break;
                  case RANK_LONGLONG:
                    *va_arg(ap, unsigned long long *)
                      = static_cast<unsigned long long>(val);
                  break;
                  case RANK_PTR:
                    *va_arg(ap, void **)
                      = reinterpret_cast<void *>(static_cast<uintptr_t>(val));
                  break;
                }
              }
            break;

            case 'f':   // Preliminary float value parsing
            case 'g':
            case 'G':
            case 'e':
            case 'E':
              q = SkipSpace(stream);
              if (q <= 0) {
                bail = BAIL_EOF;
                break;
              }

              {
              double fval = streamtofloat(stream);
              if (!(flags & FL_SPLAT)) {
                if (rank == RANK_INT)
                  *va_arg(ap, float *) = static_cast<float>(fval);
                else if (rank == RANK_LONG)
                  *va_arg(ap, double *) = static_cast<double>(fval);
                converted++;
              }
              }
            break;

            case 'c':               // Character
              width = (flags & FL_WIDTH) ? width : 1; // Default width == 1
              sarg = va_arg(ap, char *);
              while (width--) {
                if ((q = fgetc(stream)) <= 0) {
                  bail = BAIL_EOF;
                  break;
                }
                if (!(flags & FL_SPLAT)) {
                  *sarg++ = q;
                  converted++;
                }
              }
            break;

            case 's':               // String
            {
              char *sp;
              sp = sarg = va_arg(ap, char *);
              while (width--) {
                q = fgetc(stream);
                if (isspace(static_cast<unsigned char>(q)) || q <= 0) {
                  ungetc(q, stream);
                  break;
                }
                if (!(flags & FL_SPLAT)) *sp = q;
                sp++;
              }
              if (sarg == sp) {
                bail = BAIL_EOF;
              } else if (!(flags & FL_SPLAT)) {
                *sp = '\0'; // Terminate output
                converted++;
              } else {
              }
            }
            break;

            case '[':   // Character range
              sarg = va_arg(ap, char *);
              state = ST_MATCH_INIT;
              matchinv = 0;
              memset(matchmap, 0, sizeof matchmap);
            break;

            case '%':   // %% sequence
              if (fgetc(stream) != '%' )
                bail = BAIL_ERR;
            break;

            default:    // Anything else
              bail = BAIL_ERR;  // Unknown sequence
            break;
          }
        }
      break;

      case ST_MATCH_INIT:   // Initial state for %[ match
        if (ch == '^' && !(flags & FL_INV)) {
          matchinv = 1;
        } else {
          SetBit(matchmap, static_cast<unsigned char>(ch));
          state = ST_MATCH;
        }
      break;

      case ST_MATCH:    // Main state for %[ match
        if (ch == ']') {
          goto match_run;
        } else if (ch == '-') {
          range_start = static_cast<unsigned char>(ch);
          state = ST_MATCH_RANGE;
        } else {
          SetBit(matchmap, static_cast<unsigned char>(ch));
        }
      break;

      case ST_MATCH_RANGE:    // %[ match after -
        if (ch == ']') {
          SetBit(matchmap, static_cast<unsigned char>('-'));
          goto match_run;
        } else {
          int i;
          for (i = range_start ; i < (static_cast<unsigned char>(ch)) ; i++)
          SetBit(matchmap, i);
          state = ST_MATCH;
        }
      break;

      match_run:      // Match expression finished
        char* oarg = sarg;
        while (width) {
          q = fgetc(stream);
          unsigned char qc = static_cast<unsigned char>(q);
          if (q <= 0 || !(TestBit(matchmap, qc)^matchinv)) {
            ungetc(q, stream);
            break;
          }
          if (!(flags & FL_SPLAT)) *sarg = q;
          sarg++;
        }
        if (oarg == sarg) {
          bail = (q <= 0) ? BAIL_EOF : BAIL_ERR;
        } else if (!(flags & FL_SPLAT)) {
          *sarg = '\0';
          converted++;
        }
      break;
    }
  }

  if (bail == BAIL_EOF && !converted)
    converted = -1;   // Return EOF (-1)

  return converted;
}
Esempio n. 7
0
void CRC_main
(
	uint_32 initial_data
)
{
  uint_32  crc_error=0;
  uint_32  poly;
  uint_32  tot;
  uint_32  totr;
  uint_32  fxor;
  uint_32  tcrc;  
  uint_8   gbQuit = 0;
  uint_32  bByteCount;
  uint_8   ch;
  uint_32  seed,crc;
  uint_8   mode = 1;
 
  isCRC16 = 1;
  printf("\n====== CRC Lab ==========\r\n"); 
  do
   {
     if (mode == 1){
            mode = 0;
     			printf("\nPlease select CRC width (16-bit/32-bit):\r\n");
     			printf("1. CRC16\n");
     			printf("2. CRC32\n");
     			printf("select:");
     			do{
     			  ch = fgetc(stdin);
     			}while ((ch != '1') && (ch != '2'));
     			printf("%c\r\n",ch);
     			isCRC16 = !(ch-'1');
     			
     			printf("\r\nPlease select CRC polynomial:\r\n");
     			printf("1. poly = 0x1021 (CRC-CCITT)\r\n");
     			printf("2. poly = 0x8408 (XMODEM)\r\n");
     			printf("3. poly = 0x8005 (ARC)\r\n");
     			printf("4. poly = 0x04C11DB7 (CRC32) \r\n");
     			printf("5. others\r\n");
     			printf("select:");
     			do{
     			  ch = fgetc(stdin); //scanf("%c", &ch);     
     			}while(!((ch < '6') && (ch > '0')));
     			printf("%c\r\n",ch);
     			if(ch == '5')
     			{
     			  printf("Please enter a polynomial in hex format:"); 
     			  poly = Input_Word();
     			}
     			else
     			{
     			  poly = polyTab[ch-'1'];
     			}
     			tcrc = (isCRC16)? 0: 1;                // width of CRC   
     			
     			printf("\r\nPlease select type of Transpose for input:\r\n");
     			printf("1. No Transposition\r\n");
     			printf("2. Only transpose bits in a byte\r\n");
     			printf("3. Transpose both bits and bytes\r\n");
     			printf("4. Only transpose bytes\r\n");
     			printf("select:");
     			do{
     			  ch = fgetc(stdin);
     			}while (!((ch < '5') && (ch > '0')));
     			printf("ch = %c \r\n",ch);
     			tot = ch - '1';
     			
     			printf("\r\nPlease select type of Transpose for Read:\r\n");
     			printf("1. No Transposition\r\n");
     			printf("2. Only transpose bits in a byte\r\n");
     			printf("3. Transpose both bits and bytes\r\n");
     			printf("4. Only transpose bytes\r\n");
     			printf("select:");
     			do{
     			  ch = fgetc(stdin);
     			}while (!((ch < '5') && (ch > '0')));
     			printf("ch = %c\r\n",ch);
     			totr = ch - '1';
     			
     			printf("XOR final checksum (y/n)?");
     			do{
     			  ch = fgetc(stdin);
     			}while ((ch != 'y') && (ch != 'n'));     
     			printf("ch = %c\r\n",ch);
     			fxor = (ch == 'y')? 1: 0;
     			
     			 printf("Please enter seed in hex:");
     			 seed = Input_Word();
     	}		
      printf("\r\nPlease enter an ASCII Message:");
      bByteCount = Input_Message(&strMsg[0]);
      crc_error=CRC_Config(poly,tot,totr,fxor,tcrc);  
      if(isCRC16)
      {
        crc = CRC_Cal_16(seed, &strMsg[0], bByteCount);
        printf("\r\n CRC result = %#04.4x\r\n",(crc & 0x0000FFFFL));
      }
      else
      {
        crc = CRC_Cal_32(seed, &strMsg[0], bByteCount);
        printf("\r\n CRC result = %#08.8x\r\n",crc);        
      }
      printf("Press any key to enter new data...,except 'q' to quit, 'c' to re-configuration !\r\n");
      do
      {
        ch = fgetc(stdin);
      }while( !ch );
      if(ch == 'q')
      {
        gbQuit = 1;
      }           
      if(ch == 'c')
      {
        mode = 1;
      }           
   }while(!gbQuit);
    
  gbQuit = 0;
  printf("Demo is quited!\r\n");
}
Esempio n. 8
0
int getchar(void){
	return fgetc(stdin);
}
Esempio n. 9
0
draw_pic(char filename1[30])
{
    int width,height;
    unsigned char c1,c2,c3,c4;
    int     ix, iy, i, j, inten, status, ip;
    double   x, y, tnew[2], told[2], retval, sigma[2], temp;
    double   rate, t0, t1, time;
    FILE *fd;
    char host[128];
    unsigned char r,g,b;
    int c;
    int screen;
    int ops;
    double flops;
    char filename[80];
    init_color();

    
     fd=fopen(filename1,"r");
     if (!fd) 
     fd=fopen("povray.out","r");
     if (!fd) { printf("\n file open error!"); exit(1); }
     c1=fgetc(fd); c2=fgetc(fd);
     c3=fgetc(fd); c4=fgetc(fd); 
     
     WIDTH=width=c1*256+c2; 
     HEIGHT=height=c3*256+c4;
     fflush(stdout);

/**  Image mapping ***/

    screen=DefaultScreen( mydisplay );
    depth=DefaultDepth(mydisplay, screen);
    if (depth==1)
    {
    format=XYPixmap;
    bitmap_pad=32;
    }
    else 
    {
     format=ZPixmap;
     bitmap_pad=8;
     if (depth>8) bitmap_pad=32;
    }
     image=XCreateImage(mydisplay, DefaultVisual(mydisplay,screen),
                        depth, format, 0, 0,
                        width, height, bitmap_pad,0);

     if (image==0)
      { printf("\n IMAGE structure allocate error!");
      }
     else
     {
      image->data=malloc(image->bytes_per_line * height);
      if (image->data ==0)
      printf("\n IMAGE memory allocate error!");
     }
     


/* ---- get image ----^^^^ */

                        for(i=1;i<=height;i++)
                       { 
                        int LINE_Y;
                        c1=fgetc(fd);
                        c2=fgetc(fd);
                        LINE_Y=c1*256+c2;
                        for(j=1;j<=width;j++)
                        {
                        int cc;
                        r=fgetc(fd); 
                        g=fgetc(fd);  
                        b=fgetc(fd);   
                        r=get_level(r);
                        g=get_level(g);
                        b=get_level(b);
                        cc=r*6*6+g*6+b;
                        c=scren[j][i]=cc;
			XSetForeground( mydisplay,
                                        mygc, C[c].pixel);
			XDrawPoint( mydisplay, 
                                    mywindow,
                                    mygc, j,LINE_Y );
                        XPutPixel(image,j,LINE_Y, C[c].pixel);
                         }
                       }

    	XFlush( mydisplay );
        XPutImage(mydisplay,mywindow,mygc,image,
                  1,1,1,1,width,height);
}
int main(int argc, char *argv[])
{
#define NUMJP2 32
  int i, c = 0;
  long offets[NUMJP2];
  char buffer[512];
#define BUFLEN 4096
  int cont = 1;
  FILE *f;
  size_t nread;
  char haystack[BUFLEN];
  const char needle[] = "JPXDecode";

  const size_t nlen = strlen( needle );
  const size_t flen = BUFLEN - nlen;
  char *fpos = haystack + nlen;
  const char *filename;
  if( argc < 2 ) return 1;

  filename = argv[1];

  memset( haystack, 0, nlen );

  f = fopen( filename, "rb" );
  while( cont )
    {
    const char *ret;
    size_t hlen;
    nread = fread(fpos, 1, flen, f);
    hlen = nlen + nread;
    ret = memmem( haystack, hlen, needle, nlen);
    if( ret )
      {
      const long cpos = ftell(f);
      const ptrdiff_t diff = ret - haystack;
      assert( diff >= 0 );
      /*fprintf( stdout, "Found it: %lx\n", (ptrdiff_t)cpos - (ptrdiff_t)hlen + diff);*/
      offets[c++] = (ptrdiff_t)cpos - (ptrdiff_t)hlen + diff;
      }
    cont = (nread == flen);
    memcpy( haystack, haystack + nread, nlen );
    }

  assert( feof( f ) );

  for( i = 0; i < c; ++i )
    {
    int s, len = 0;
    char *r;
    const int ret = fseek(f, offets[i], SEEK_SET);
    assert( ret == 0 );
    r = fgets(buffer, sizeof(buffer), f);
    assert( r );
    /*fprintf( stderr, "DEBUG: %s", r );*/
    s = sscanf(r, "JPXDecode]/Length  %d/Width %*d/BitsPerComponent %*d/Height %*d", &len);
    assert( s == 1 );
      {
      FILE *jp2;
      int j;
      char jp2fn[512];
      sprintf( jp2fn, "%s.%d.jp2", filename, i );
      jp2 = fopen( jp2fn, "wb" );
      for( j = 0; j < len; ++j )
        {
        int v = fgetc(f);
        int ret2 = fputc(v, jp2);
        assert( ret2 != EOF );
        }
      fclose( jp2 );
#if 0
      /* TODO need to check we reached endstream */
      r = fgets(buffer, sizeof(buffer), f);
      fprintf( stderr, "DEBUG: [%s]", r );
      r = fgets(buffer, sizeof(buffer), f);
      fprintf( stderr, "DEBUG: [%s]", r );
#endif
      }
    }
  fclose(f);

  return 0;
}
int PreProcess(char *pcSubName)//预处理子程序,完成功能每次向ScanBuffer中装入固定字长的源程序代码
{
	static char fcFlag='L';
	int i;

	//将源程序中读入剔除空格注视等放到buffer
	char * pcCurrent=0;//只是当前要赋值的字节
	char ** ppcCurrent=&pcCurrent;//指向指针的指针
	char * pcStart;//指向数组的开始,计算偏移量用
	char * pcTemp;//临时变量,初始化用
	FILE * pfSourceFile;//指向要打开的源程序文件

	//初始化pcCurrent确认当前要装入的缓冲区
	if(fcFlag=='L') 
	{
		pcCurrent=acScanBufL;
		pcStart=acScanBufL;
	}
	else
	{
		pcCurrent=acScanBufR;
		pcStart=acScanBufR;
	}

	//初始化当前缓冲区为空字符
	pcTemp=pcCurrent;
	for(i=0;i<SBUFSIZE;i++)
	{
		*pcTemp=0;
		pcTemp++;
	}

	//打开文件
	pfSourceFile=fopen("test.txt","r");
	if(pfSourceFile==NULL) 
	{
		printf("The file %s was not opened\n",pcSubName);//判断文件打开是否成功
		exit(0);//装入失败退出
	}
	else//打开成功读入
	{
		if(fseek(pfSourceFile,lnOffset,SEEK_SET))//移动文件指针到应该的位置
		{
			perror("Fseek failed");
			exit(1);//移动光标失败退出
		}

		while((pcCurrent-pcStart)!=SBUFSIZE)//循环读入指定长度字符
		{
			char cTemp;//临时变量
			cTemp=fgetc(pfSourceFile);//读入一个字符
			cTemp=CheckChar(pfSourceFile,ppcCurrent,cTemp,'N');//获取一个合法的字符

			if(cTemp==0x20)
			{
				*pcCurrent=cTemp;
				pcCurrent++;
				*pcCurrent='#';//程序结束
				break;//判断是否到文件末尾
			}

			*pcCurrent=cTemp;//若刚才输入的不为空格也没结束则输入到缓冲区
			pcCurrent++;
		
		}	

		//修改偏移量为当前偏移量,为下次读入用
		lnOffset=ftell(pfSourceFile);
		
		//关闭文件
		fclose(pfSourceFile);

		//修改fcFlag为下次再次装入,更改缓冲区
		if(fcFlag=='L') fcFlag='R';
		else fcFlag='L';
	}

	return 3;
}
Esempio n. 12
0
void handle_request() {
  // read request
  int message_len;
  if((message_len = recv(client_socket, &recv_buffer, sizeof(recv_buffer), 0)) == -1) {
    perror("recv");
    exit(-1);
  }

  // parse status line "Method SP Request-URI SP HTTP-Version CRLF";
  sscanf(recv_buffer, "%s %s", request_method, request_uri);

  // No uri path given, assume index.html
  if(strlen(request_uri)==1) {
    strcpy(request_uri, "/index.html");
  }

  // open requested file
  sprintf(filename, "%s%s", www_root, request_uri);

  FILE *filepointer;
  int character;
  filepointer=fopen(filename, "r"); /* filepointer points to data.txt */
  if (filepointer==NULL) { /* error opening file returns NULL */
    fprintf(stderr, "Requsted file %s not found, sent 404 as response to (METHOD:%s URI:%s)\n",
            filename, request_method, request_uri);
    // write status
    if(send(client_socket, status_line_not_found, strlen(status_line_not_found), 0) == -1) {
      perror("send");
      exit(-1);
    }
    // close
    if(close(client_socket) == -1) {
      perror("close");
      exit(-1);
    }
    return;
  }

  // write status
  if(send(client_socket, status_line_ok, strlen(status_line_ok), 0) == -1) {
    perror("send");
    exit(-1);
  }

  // write header/body reparator  
  if(send(client_socket, "\x0D\x0A", 2, 0) == -1) {
    perror("send");
    exit(-1);
  }

 /* while character is not end of file */
  while ((character=fgetc(filepointer)) != EOF) {
    send_buffer[0] = character;
    // write body
    if(send(client_socket, send_buffer, 1, 0) == -1) {
      perror("send");
      exit(-1);
    }
  }
  fclose(filepointer); /* close the file */
  
  // close
  if(close(client_socket) == -1) {
    perror("close");
    exit(-1);
  }
}
Esempio n. 13
0
TypeNameFossilIntTab *readFossilIntTab(FILE *f) {
    int sizeBuf;
    char c;
    TypeNameFossilIntTab *res;

    res = (TypeNameFossilIntTab *) malloc(sizeof(TypeNameFossilIntTab));
    sizeBuf = INC_FOSSIL_ITEM;
    res->name = (char**) malloc(sizeBuf*sizeof(char*));
    res->fossilIntTab = (TypeFossilIntTab*) malloc(sizeBuf*sizeof(TypeFossilIntTab));
    res->size = 0;
    do {
        char *tmp;
        int i;
        tmp = (char*) malloc((MAX_NAME_SIZE+1)*sizeof(char));
        for(c = fgetc(f); c != EOF && issepline(c); c = fgetc(f));
        if(c == '\'' || c == '"') {
            c = fgetc(f);
            for(i=0; i<MAX_NAME_SIZE && c != EOF && c != '\'' && c != '"'; i++) {
                tmp[i] = c;
                c = fgetc(f);
            }
            if(c == '\'' || c == '"')
                c = fgetc(f);
        } else {
            for(i=0; i<MAX_NAME_SIZE && c !=EOF && !issep(c); i++) {
                tmp[i] = c;
                c = fgetc(f);
            }
        }
        if(i == MAX_NAME_SIZE)
            exitProg(ErrorExec, "Name too much long...");
        tmp[i++] = '\0';
        if(i>1) {
            char bof[MAX_NAME_SIZE+1];
            int sizeFossilIntBuf = INC_FOSSIL_ITEM;
            if(res->size >= sizeBuf) {
                sizeBuf += INC_FOSSIL_ITEM;
                res->name = (char**) realloc((void*) res->name, sizeBuf*sizeof(char*));
                res->fossilIntTab = (TypeFossilIntTab*) realloc((void*) res->fossilIntTab, sizeBuf*sizeof(TypeFossilIntTab));
            }
            res->name[res->size] = (char *) realloc((void*) tmp, i*sizeof(char));
            fixSpace(res->name[res->size]);
            res->fossilIntTab[res->size].size = 0;
            res->fossilIntTab[res->size].fossilInt = (TypeTimeInterval*) malloc(sizeFossilIntBuf*sizeof(TypeTimeInterval));
            for(; c != EOF && issep(c); c = fgetc(f));
            while(c != EOF && !isline(c)) {
                for(i=0; c != EOF && !issepline(c) && i<MAX_NAME_SIZE; i++) {
                    bof[i] = c;
                    c = fgetc(f);
                }
                bof[i++] = '\0';
                if(res->fossilIntTab[res->size].size>=sizeFossilIntBuf) {
                    sizeFossilIntBuf += INC_FOSSIL_ITEM;
                    res->fossilIntTab[res->size].fossilInt = (TypeTimeInterval*) realloc((void*) res->fossilIntTab[res->size].fossilInt, sizeFossilIntBuf*sizeof(TypeTimeInterval));
                }
                res->fossilIntTab[res->size].fossilInt[res->fossilIntTab[res->size].size++] = toFossilInt(bof);
DEBUG(
    printf("\"%s\"\t%s\t", tmp, bof);
    fprintFossilInt(stdout, res->fossilIntTab[res->size].fossilInt[res->fossilIntTab[res->size].size-1]);
    printf("\n");
)
                for(; c != EOF && issep(c); c = fgetc(f));
            }
            res->size++;
        } else
Esempio n. 14
0
int main(int argc, char **argv)
{
	FILE *hexfile = NULL;
	long fsize = 0;
	nibstor *nibbles = NULL;
	long nibblenum = 0;
	int byte = 0;
	char hilo = -1;
	int i = 0;
	int j = 0;
	int k = 0;
	int inststart = 0;
	unsigned char inst[5];
	uint16_t addr = 0;
	uint8_t args = 0;

	if(argc < 2)
	{
		return 0;
	}
	if(!strcmp("-i", argv[1]))
	{
		if(argc < 3)
		{
			return 0;
		}
		return interactive(argv[2]);
	}
	hexfile = fopen(argv[1], "rb");
	if(hexfile == NULL)
	{
		perror("Could not open hexfile");
		return 1;
	}
	
	fseek(hexfile, 0, SEEK_END);
	fsize = ftell(hexfile);
	if(fsize == 0)
	{
		fprintf(stderr, "File size is zero!\n");
		return 2;
	}
	rewind(hexfile);

	nibbles = calloc(sizeof(nibstor), fsize + 1);
	if(nibbles == NULL)
	{
		perror("Could not allocate memory");
		return 3;
	}

	byte = fgetc(hexfile);
	hilo = 0;
	while(byte != EOF)
	{
		nibbles[i].hi = (char)((byte >> 4) & 0xF);
		nibbles[i].lo = (char)(byte & 0xF);
		i++;
		byte = fgetc(hexfile);
	}
	nibblenum = i;
	fclose(hexfile);
	printf("      ");
	for(i = 0; i < 5; i++)
	{
		printf("%X ", i);
	}
	puts("");
	printf("%04X: ", 0);
	for(i = 0; i < nibblenum; i++)
	{
		printf("%X ", nibbles[i].hi);
		inst[k] = nibbles[i].hi;
		k++;
		j++;
		if((j % 5) == 0)
		{
			k = 0;
			printf("   ");
			printdisasm(inst);
			puts("");
			printf("%04X: ", j);
		}
		printf("%X ", nibbles[i].lo);
		inst[k] = nibbles[i].lo;
		k++;
		j++;
		if((j % 5) == 0)
		{
			k = 0;
			printf("   ");
			printdisasm(inst);
			if(i+1 != nibblenum)
			{
				puts("");
				printf("%04X: ", j);
			}
		}
	}
	if(k != 0)
	{
		printf("   ");
		for(i = 0; i < (5-k); i++)
		{
			printf("  ");
		}
		printf(".data %i 0x", k);
		for(i = 0; i < k; i++)
		{
			printf("%X", inst[i]);
		}
		puts("");
	}
	free(nibbles);
	return 0;
}
Esempio n. 15
0
/*
  load a node from the file
  Params: fp - the input stream
          error - return for error
  Returns: node loaded.
  Notes: recursive. Expects the opening parenthesis to have been eaten
 */
NEWICKNODE *TreeOPE::loadnode(FILE *fp, int *error)
{
  NEWICKNODE *answer = NULL;
  int err;
  NEWICKNODE *child = 0;
  int ch;

  answer = (NEWICKNODE *) malloc(sizeof(NEWICKNODE));
  //printf("sizeof(NEWICKNODE) = %d\n", sizeof(NEWICKNODE));
  if(!answer)
  {
    err = -1;
    goto error_exit;
  }

  answer->Nchildren = 0;
  answer->label = 0;
  answer->child = 0;
  answer->hv1 = 0;
  answer->hv2 = 0;
  answer->bitstr = NULL;

  skipspace(fp);
  do
  {
    ch = fgetc(fp);
    if(ch == '(')
    {
      child = loadnode(fp, &err);
      if(!child)
        goto error_exit;

      if(addchild(answer, child ) == -1)
      {
        err = -1;
        goto error_exit;
      }
      child = 0;
    }
    else
    {
      ungetc(ch, fp);
      child = loadleaf(fp, &err);
      if(!child)
        goto error_exit;

      if(addchild(answer, child) == -1)
      {
        err = -1;
        goto error_exit;
      }
      child = 0;
    }
    skipspace(fp);
    ch = fgetc(fp);
  } while(ch == ',');

  if(ch == ')')
  {
    answer->label = readlabelandweight(fp, &answer->weight, &err);
    if(err)
      goto error_exit;
  }
  else
  {
    err = -2;
    goto error_exit;
  }

  if(error)
    *error = 0;
  return answer;

 error_exit:
  if(child)
    killnoder(child);
  killnoder(answer);
  if(error)
    *error = err;
  return 0;
}
Esempio n. 16
0
static int getWord( FILE *fp, wordlist **list, word *w, unsigned *os )
{
    static int           ret  = 0;

    char                *tmp  = NULL;
    int                  ch   = 0;
    int                  pv   = 0;
    int                  ppv  = 0;

    ret &= ~OUT_OF_MEM;
    if( w->len == 0  ||  w->len >= w_size ) {
        ret = 0;
        while( 1 ) {
            if( w->len >= w_size ) {
                w_size += MIN_WORD_LEN;
                tmp  = (char *) realloc( w_buff, w_size );
                if( tmp == NULL ) {
                    w_size -= MIN_WORD_LEN;
                    return( OUT_OF_MEM );
                }
                w_buff = tmp;
            }
            ppv = pv;
            pv  = ch;
            ch  = fgetc( fp );
            if( ch == '\n'  ||  ch == '\t'  ||  ch == ' '  ||  ch == EOF ) {
                break;
            } else {
                *os += 1;
                w_buff[ w->len ] = ch;
                w->len++;
            }
        }
        while( 1 ) {
            if( ch == ' ' ) {
                w->spc++;
                *os += 1;
            } else if( ch == '\t' ) {
                w->spc += 8 - *os % 8;
                *os += 8 - *os % 8;
            } else {
                break;
            }
            ch = fgetc( fp );
        }

        if( w->len > 0 ) {
            w_buff[ w->len ] = '\0';
        }
        if( ch == EOF ) {
            *os = 0;
            w->spc = 1;
            ret |= END_FILE;
        } else if( ch == '\n' ) {
            *os = 0;
            w->spc = 1;
            ret |= END_LINE;
        } else {
            ungetc( ch, fp );
        }

        if( w->spc == 0 ) {
            w->spc = 1;
        } else if( f_mode & FMT_NOSPACE ) {
            if( pv == '.'  ||  pv == '?'  ||  pv == '!' ) {
                if( isupper( ppv ) ) {
                    w->spc = 1;
                } else {
                    w->spc = 2;
                }
            } else {
                w->spc = 1;
            }
        }
    }
    w->text = insertWord( list, w_buff, w->len );
    if( w->text == NULL ) {
        ret |= OUT_OF_MEM;
    }
    return( ret );
}
Esempio n. 17
0
int std::getc( FILE *f) {
	return fgetc(f);
}
Esempio n. 18
0
File: geod.c Progetto: Maasik/proj.4
	static void	/* file processing function */
process(FILE *fid) {
	char line[MAXLINE+3], *s;

	for (;;) {
		++emess_dat.File_line;
		if (!(s = fgets(line, MAXLINE, fid)))
			break;
		if (!strchr(s, '\n')) { /* overlong line */
			int c;
			strcat(s, "\n");
			/* gobble up to newline */
			while ((c = fgetc(fid)) != EOF && c != '\n') ;
		}
		if (*s == tag) {
			fputs(line, stdout);
			continue;
		}
		phi1 = dmstor(s, &s);
		lam1 = dmstor(s, &s);
		if (inverse) {
			phi2 = dmstor(s, &s);
			lam2 = dmstor(s, &s);
			geod_inv();
		} else {
			al12 = dmstor(s, &s);
			geod_S = strtod(s, &s) * to_meter;
			geod_pre();
			geod_for();
		}
		if (!*s && (s > line)) --s; /* assumed we gobbled \n */
		if (pos_azi) {
			if (al12 < 0.) al12 += M_TWOPI;
			if (al21 < 0.) al21 += M_TWOPI;
		}
		if (fullout) {
			printLL(phi1, lam1); TAB;
			printLL(phi2, lam2); TAB;
			if (oform) {
				(void)printf(oform, al12 * RAD_TO_DEG); TAB;
				(void)printf(oform, al21 * RAD_TO_DEG); TAB;
				(void)printf(osform, geod_S * fr_meter);
			}  else {
				(void)fputs(rtodms(pline, al12, 0, 0), stdout); TAB;
				(void)fputs(rtodms(pline, al21, 0, 0), stdout); TAB;
				(void)printf(osform, geod_S * fr_meter);
			}
		} else if (inverse)
			if (oform) {
				(void)printf(oform, al12 * RAD_TO_DEG); TAB;
				(void)printf(oform, al21 * RAD_TO_DEG); TAB;
				(void)printf(osform, geod_S * fr_meter);
			} else {
				(void)fputs(rtodms(pline, al12, 0, 0), stdout); TAB;
				(void)fputs(rtodms(pline, al21, 0, 0), stdout); TAB;
				(void)printf(osform, geod_S * fr_meter);
			}
		else {
			printLL(phi2, lam2); TAB;
			if (oform)
				(void)printf(oform, al21 * RAD_TO_DEG);
			else
				(void)fputs(rtodms(pline, al21, 0, 0), stdout);
		}
		(void)fputs(s, stdout);
	}
}
Esempio n. 19
0
int main(int argc, char *argv[]){
	FILE *fp;
	int c;

// ./mcat-lib file
// afficher le fichier
	if(argc==2){
		if(!(fp=fopen(argv[1],"r"))){
			perror("Error opening file.");
			exit(EXIT_FAILURE);
		}

		c = fgetc(fp);
		while(c!=EOF){
			printf("%c",(char)c);
			c = fgetc(fp);
		}
		fclose(fp);
	}

// ./mcat-lib file1 file2 file3
// concat file1, file2 et exporter a file3
	else if(argc==4){
		FILE *fp2, *fp3;
		if( !(fp=fopen(argv[1],"r")) || !(fp2=fopen(argv[2],"r")) || !(fp3=fopen(argv[3],"w+")) ){
			perror("Error opening/creating file.");
			exit(EXIT_FAILURE);
		}

		c = fgetc(fp);
		while(c!=EOF){
			fputc(c,fp3);
			c = fgetc(fp);
		}
		fclose(fp);
		c = fgetc(fp2);
		while(c!=EOF){
			fputc(c,fp3);
			c = fgetc(fp2);
		}
		fclose(fp2);
	}

// ./mcat-lib file1 file2 > file3
// concat file1, file2 et exporter a file3
	else if(argc==3){
		FILE *fp2, *fp3;
		if( !(fp=fopen(argv[1],"r")) || !(fp2=fopen(argv[2],"r"))){
			perror("Error opening file.");
			exit(EXIT_FAILURE);
		}

		c = fgetc(fp);
		while(c!=EOF){
			printf("%c",(char)c);
			c = fgetc(fp);
		}
		fclose(fp);
		c = fgetc(fp2);
		while(c!=EOF){
			printf("%c",(char)c);
			c = fgetc(fp2);
		}
		fclose(fp2);
	}
}
Esempio n. 20
0
int imap_append_message (CONTEXT *ctx, MESSAGE *msg)
{
  IMAP_DATA* idata;
  FILE *fp;
  char buf[LONG_STRING];
  char mbox[LONG_STRING];
  char mailbox[LONG_STRING];
  char internaldate[IMAP_DATELEN];
  char imap_flags[SHORT_STRING];
  size_t len;
  progress_t progressbar;
  size_t sent;
  int c, last;
  IMAP_MBOX mx;
  int rc;

  idata = (IMAP_DATA*) ctx->data;

  if (imap_parse_path (ctx->path, &mx))
    return -1;

  imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
  if (!*mailbox)
    strfcpy (mailbox, "INBOX", sizeof (mailbox));

  if ((fp = fopen (msg->path, "r")) == NULL)
  {
    mutt_perror (msg->path);
    goto fail;
  }

  /* currently we set the \Seen flag on all messages, but probably we
   * should scan the message Status header for flag info. Since we're
   * already rereading the whole file for length it isn't any more
   * expensive (it'd be nice if we had the file size passed in already
   * by the code that writes the file, but that's a lot of changes.
   * Ideally we'd have a HEADER structure with flag info here... */
  for (last = EOF, len = 0; (c = fgetc(fp)) != EOF; last = c)
  {
    if(c == '\n' && last != '\r')
      len++;

    len++;
  }
  rewind (fp);

  mutt_progress_init (&progressbar, _("Uploading message..."),
		      M_PROGRESS_SIZE, NetInc, len);

  imap_munge_mbox_name (idata, mbox, sizeof (mbox), mailbox);
  imap_make_date (internaldate, msg->received);

  imap_flags[0] = imap_flags[1] = 0;
  if (msg->flags.read)
    safe_strcat (imap_flags, sizeof (imap_flags), " \\Seen");
  if (msg->flags.replied)
    safe_strcat (imap_flags, sizeof (imap_flags), " \\Answered");
  if (msg->flags.flagged)
    safe_strcat (imap_flags, sizeof (imap_flags), " \\Flagged");
  if (msg->flags.draft)
    safe_strcat (imap_flags, sizeof (imap_flags), " \\Draft");

  snprintf (buf, sizeof (buf), "APPEND %s (%s) \"%s\" {%lu}", mbox,
            imap_flags + 1,
	    internaldate,
	    (unsigned long) len);

  imap_cmd_start (idata, buf);

  do
    rc = imap_cmd_step (idata);
  while (rc == IMAP_CMD_CONTINUE);

  if (rc != IMAP_CMD_RESPOND)
  {
    char *pc;

    dprint (1, (debugfile, "imap_append_message(): command failed: %s\n",
		idata->buf));

    pc = idata->buf + SEQLEN;
    SKIPWS (pc);
    pc = imap_next_word (pc);
    mutt_error ("%s", pc);
    mutt_sleep (1);
    safe_fclose (&fp);
    goto fail;
  }

  for (last = EOF, sent = len = 0; (c = fgetc(fp)) != EOF; last = c)
  {
    if (c == '\n' && last != '\r')
      buf[len++] = '\r';

    buf[len++] = c;

    if (len > sizeof(buf) - 3)
    {
      sent += len;
      flush_buffer(buf, &len, idata->conn);
      mutt_progress_update (&progressbar, sent, -1);
    }
  }

  if (len)
    flush_buffer(buf, &len, idata->conn);

  mutt_socket_write (idata->conn, "\r\n");
  safe_fclose (&fp);

  do
    rc = imap_cmd_step (idata);
  while (rc == IMAP_CMD_CONTINUE);

  if (!imap_code (idata->buf))
  {
    char *pc;

    dprint (1, (debugfile, "imap_append_message(): command failed: %s\n",
		idata->buf));
    pc = idata->buf + SEQLEN;
    SKIPWS (pc);
    pc = imap_next_word (pc);
    mutt_error ("%s", pc);
    mutt_sleep (1);
    goto fail;
  }

  FREE (&mx.mbox);
  return 0;

 fail:
  FREE (&mx.mbox);
  return -1;
}
Esempio n. 21
0
/*
 * Allocate and read a binary string from file.
 * The strings are nl-ended or zero-ended, depending on the sort setting.
 */
struct bwstring *
bwsfgetln(FILE *f, size_t *len, bool zero_ended, struct reader_buffer *rb)
{
	wint_t eols;

	eols = zero_ended ? btowc('\0') : btowc('\n');

	if (!zero_ended && (MB_CUR_MAX > 1)) {
		wchar_t *ret;

		ret = fgetwln(f, len);

		if (ret == NULL) {
			if (!feof(f))
				err(2, NULL);
			return (NULL);
		}
		if (*len > 0) {
			if (ret[*len - 1] == (wchar_t)eols)
				--(*len);
		}
		return (bwssbdup(ret, *len));

	} else if (!zero_ended && (MB_CUR_MAX == 1)) {
		char *ret;

		ret = fgetln(f, len);

		if (ret == NULL) {
			if (!feof(f))
				err(2, NULL);
			return (NULL);
		}
		if (*len > 0) {
			if (ret[*len - 1] == '\n')
				--(*len);
		}
		return (bwscsbdup((unsigned char*)ret, *len));

	} else {
		*len = 0;

		if (feof(f))
			return (NULL);

		if (2 >= rb->fgetwln_z_buffer_size) {
			rb->fgetwln_z_buffer_size += 256;
			rb->fgetwln_z_buffer = sort_realloc(rb->fgetwln_z_buffer,
			    sizeof(wchar_t) * rb->fgetwln_z_buffer_size);
		}
		rb->fgetwln_z_buffer[*len] = 0;

		if (MB_CUR_MAX == 1)
			while (!feof(f)) {
				int c;

				c = fgetc(f);

				if (c == EOF) {
					if (*len == 0)
						return (NULL);
					goto line_read_done;
				}
				if (c == eols)
					goto line_read_done;

				if (*len + 1 >= rb->fgetwln_z_buffer_size) {
					rb->fgetwln_z_buffer_size += 256;
					rb->fgetwln_z_buffer = sort_realloc(rb->fgetwln_z_buffer,
					    SIZEOF_WCHAR_STRING(rb->fgetwln_z_buffer_size));
				}

				rb->fgetwln_z_buffer[*len] = c;
				rb->fgetwln_z_buffer[++(*len)] = 0;
			}
		else
			while (!feof(f)) {
				wint_t c = 0;

				c = fgetwc(f);

				if (c == WEOF) {
					if (*len == 0)
						return (NULL);
					goto line_read_done;
				}
				if (c == eols)
					goto line_read_done;

				if (*len + 1 >= rb->fgetwln_z_buffer_size) {
					rb->fgetwln_z_buffer_size += 256;
					rb->fgetwln_z_buffer = sort_realloc(rb->fgetwln_z_buffer,
					    SIZEOF_WCHAR_STRING(rb->fgetwln_z_buffer_size));
				}

				rb->fgetwln_z_buffer[*len] = c;
				rb->fgetwln_z_buffer[++(*len)] = 0;
			}

line_read_done:
		/* we do not count the last 0 */
		return (bwssbdup(rb->fgetwln_z_buffer, *len));
	}
}
Esempio n. 22
0
main() {
    char c;
    FILE *fp;
    int  fromlen;
    char hostname[64];
    struct hostent *hp;
    int  i, s, ns;
    struct sockaddr_in sin, fsin;

    gethostname(hostname, sizeof(hostname));

    if ((hp = gethostbyname(hostname)) == NULL) {
        fprintf(stderr, "%s: host unknown.\n", hostname);
        exit(1);
    }

    if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("server: socket");
        exit(1);
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(1234);
    bcopy(hp->h_addr, &sin.sin_addr, hp->h_length);

    if (bind(s, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
        perror("server: bind");
        exit(1);
    }

    if (listen(s, 5) < 0) {
        perror("server: listen");
        exit(1);
    }

    if ((ns = accept(s, (struct sockaddr*)&fsin, &fromlen)) < 0 ) {
        perror("server: accept");
        exit(1);
    }

    fp = fdopen(ns, "r");
    
    for (i=0; i < NSTRS; i++) {
        send(ns, strs[i], strlen(strs[i]), 0);
    }

    sleep(20);

    for (i=0; i < NSTRS; i++) {
        while ((c=fgetc(fp)) != EOF) {
            putchar(c);

            if (c == '\n') {
                break;
            }
        }
    }

    shutdown(s, 2);

    exit(0);
}
Esempio n. 23
0
/*******************************************************************************
 *	NOME:		refresh_messages
 *	FUNÇÃO:		Cuida da mostra de mensagens. Melhora formatacao da exibicao.
 *				Utiliza arquivos para guardar as mensagens recebidas e mostra
 * 				elas sob demanda
 *
 *	RETORNO:	void
 *******************************************************************************/
void refresh_messages(){
	int pos;		//posicao no arquivo de dados
	char check;		//checa se o arquivo esta vazio ou nao
	char option;	//lida com o menu
	char buffer[100];
	int end;

	do{
		printf("Deseja:\n1-Imprimir ultimas mensagens\n2-Imprimir todas as mensagens\n3-Excluir historico completo\n4-Sair\n");

		__fpurge(stdin);
		option = getchar();
		__fpurge(stdin);

		if(option != '4'){
			sem_wait(&sem_file);

			fseek(chat_log, 0, SEEK_END);
			end = ftell(chat_log);
			fseek(chat_log, 0, SEEK_SET);

			//O primeiro caracter do arquivo indica se ele esta vazio ou nao. 0 = vazio, 1 = nao vazio.
			check = fgetc(chat_log);
			if(check == '0'){
				printf("Voce nao recebeu nenhuma mensagem. Nao ha nada para imprimir ou excluir. D:\n");
			}
			else{

				if(option == '1'){
					fread(&pos, sizeof(int), 1, chat_log);
					fseek(chat_log, pos, SEEK_SET);
					if(ftell(chat_log) == (end-1)){
						printf("Voce nao tem nenhuma nova mensagem\n");
					}
					else{
						do{
							fread(&buffer, sizeof(buffer), 1, chat_log);
							printf("%s", buffer);
						}while(ftell(chat_log) != end);
					}
					fseek(chat_log, 0, SEEK_END);
					pos = ftell(chat_log);
					pos--;	//Volta para o ultimo caracter que e um \0. 
					fseek(chat_log, 1, SEEK_SET);
					fwrite(&pos, sizeof(int), 1, chat_log);
				}
				else if(option == '2'){
					fread(&pos, sizeof(int), 1, chat_log);
					do{
						fread(buffer, sizeof(buffer), 1, chat_log);
						printf("%s", buffer);
					}while(ftell(chat_log) != end);
					fseek(chat_log, 0, SEEK_END);
					pos = ftell(chat_log);
					pos--; //Volta para o ultimo caracter que e um \0. 
					fseek(chat_log, 1, SEEK_SET);
					fwrite(&pos, sizeof(int), 1, chat_log);
				}
				else if(option == '3'){
					fseek(chat_log, 0, SEEK_SET);
					fputc('0', chat_log);
				}
			}
			sem_post(&sem_file);
		}
	}while(option != '4');
	sem_post(&sem_client);
}
Esempio n. 24
0
/*
===============
Host_Loadgame_f
===============
*/
void Host_Loadgame_f (void)
{
	char	name[MAX_OSPATH];
	FILE	*f;
	char	mapname[MAX_QPATH];
	float	time, tfloat;
	char	str[32768];
	const char  *start;
	int	i, r;
	edict_t	*ent;
	int	entnum;
	int	version;
	float	spawn_parms[NUM_SPAWN_PARMS];

	if (cmd_source != src_command)
		return;

	if (Cmd_Argc() != 2)
	{
		Con_Printf ("load <savename> : load a game\n");
		return;
	}

	cls.demonum = -1;		// stop demo loop in case this fails

	q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1));
	COM_DefaultExtension (name, ".sav", sizeof(name));

// we can't call SCR_BeginLoadingPlaque, because too much stack space has
// been used.  The menu calls it before stuffing loadgame command
//	SCR_BeginLoadingPlaque ();

	Con_Printf ("Loading game from %s...\n", name);
	f = fopen (name, "r");
	if (!f)
	{
		Con_Printf ("ERROR: couldn't open.\n");
		return;
	}

	fscanf (f, "%i\n", &version);
	if (version != SAVEGAME_VERSION)
	{
		fclose (f);
		Con_Printf ("Savegame is version %i, not %i\n", version, SAVEGAME_VERSION);
		return;
	}
	fscanf (f, "%s\n", str);
	for (i = 0; i < NUM_SPAWN_PARMS; i++)
		fscanf (f, "%f\n", &spawn_parms[i]);
// this silliness is so we can load 1.06 save files, which have float skill values
	fscanf (f, "%f\n", &tfloat);
	current_skill = (int)(tfloat + 0.1);
	Cvar_SetValue ("skill", (float)current_skill);

	fscanf (f, "%s\n",mapname);
	fscanf (f, "%f\n",&time);

	CL_Disconnect_f ();

	SV_SpawnServer (mapname);

	if (!sv.active)
	{
		fclose (f);
		Con_Printf ("Couldn't load map\n");
		return;
	}
	sv.paused = true;		// pause until all clients connect
	sv.loadgame = true;

// load the light styles

	for (i = 0; i < MAX_LIGHTSTYLES; i++)
	{
		fscanf (f, "%s\n", str);
		sv.lightstyles[i] = (const char *)Hunk_Strdup (str, "lightstyles");
	}

// load the edicts out of the savegame file
	entnum = -1;		// -1 is the globals
	while (!feof(f))
	{
		for (i = 0; i < (int) sizeof(str) - 1; i++)
		{
			r = fgetc (f);
			if (r == EOF || !r)
				break;
			str[i] = r;
			if (r == '}')
			{
				i++;
				break;
			}
		}
		if (i == (int) sizeof(str) - 1)
		{
			fclose (f);
			Sys_Error ("Loadgame buffer overflow");
		}
		str[i] = 0;
		start = str;
		start = COM_Parse(str);
		if (!com_token[0])
			break;		// end of file
		if (strcmp(com_token,"{"))
		{
			fclose (f);
			Sys_Error ("First token isn't a brace");
		}

		if (entnum == -1)
		{	// parse the global vars
			ED_ParseGlobals (start);
		}
		else
		{	// parse an edict

			ent = EDICT_NUM(entnum);
			memset (&ent->v, 0, progs->entityfields * 4);
			ent->free = false;
			ED_ParseEdict (start, ent);

		// link it into the bsp tree
			if (!ent->free)
				SV_LinkEdict (ent, false);
		}

		entnum++;
	}

	sv.num_edicts = entnum;
	sv.time = time;

	fclose (f);

	for (i = 0; i < NUM_SPAWN_PARMS; i++)
		svs.clients->spawn_parms[i] = spawn_parms[i];

	if (cls.state != ca_dedicated)
	{
		CL_EstablishConnection ("local");
		Host_Reconnect_f ();
	}
}
Esempio n. 25
0
static void write_joined_vtk(const char *out_name){
  FILE *fp_out;
  int nxt, nyt, nzt; /* Total number of grid cells in each dir. */
  int nxp, nyp, nzp;
  int i, j, k;
  double ox, oy, oz, dx, dy, dz;
  char type[128], variable[128], format[128];
  char t_type[128], t_variable[128], t_format[128]; /* Temporary versions */
  int retval;

  /* Count the total number of grid cells in each direction */
  nxt = nyt = nzt = 0;
  for(i=0; i<NGrid_x; i++)
    nxt += domain_3d[0][0][i].Nx;

  for(j=0; j<NGrid_y; j++)
    nyt += domain_3d[0][j][0].Ny;

  for(k=0; k<NGrid_z; k++)
    nzt += domain_3d[k][0][0].Nz;

  /* Initialize ox, oy, oz */
  ox = domain_3d[0][0][0].ox;
  oy = domain_3d[0][0][0].oy;
  oz = domain_3d[0][0][0].oz;

  /* Initialize dx, dy, dz */
  dx = domain_3d[0][0][0].dx;
  dy = domain_3d[0][0][0].dy;
  dz = domain_3d[0][0][0].dz;

  /* Count the number of grid cell corners */
  if(nxt >= 1 && dx > 0.0) nxp = nxt+1;
  else nxp = nxt; /* dx = 0.0 */

  if(nyt >= 1 && dy > 0.0) nyp = nyt+1;
  else nyp = nyt; /* dy = 0.0 */

  if(nzt >= 1 && dz > 0.0) nzp = nzt+1;
  else nzp = nzt; /* dz = 0.0 */

  /* Open the output file */
  if((fp_out = fopen(out_name,"w")) == NULL)
    join_error("Error opening the output file \"%s\"\n",out_name);

  /* Write out some header information */
  fprintf(fp_out,"# vtk DataFile Version 3.0\n");
  /* Save the comment field from the [0][0][0] vtk domain file */
  /* fprintf(fp_out,"Joined VTK files\n"); */
  fprintf(fp_out,"%s\n",domain_3d[0][0][0].comment);
  fprintf(fp_out,"BINARY\n");
  fprintf(fp_out,"DATASET STRUCTURED_POINTS\n");
  fprintf(fp_out,"DIMENSIONS %d %d %d\n", nxp, nyp, nzp);
  fprintf(fp_out,"ORIGIN %e %e %e\n", ox, oy, oz);
  fprintf(fp_out,"SPACING %e %e %e\n", dx, dy, dz);
  fprintf(fp_out,"CELL_DATA %d\n",nxt*nyt*nzt);

  while(1){
    for(k=0; k<NGrid_z; k++){
      for(j=0; j<NGrid_y; j++){
	for(i=0; i<NGrid_x; i++){
	  if(i == 0 && j == 0 && k == 0){
	    retval = fscanf(domain_3d[k][j][i].fp,"%s %s %s\n",
			    type, variable, format);

	    if(retval == EOF){ /* Assuming no errors, we are done... */
	      fclose(fp_out);
	      return;
	    }

	    if(strcmp(format, "float") != 0){
	      fclose(fp_out);
	      join_error("Expected \"float\" format, found \"%s\"\n",format);
	    }
	  }
	  else{
	    retval = fscanf(domain_3d[k][j][i].fp,"%s %s %s\n",
			    t_type, t_variable, t_format);

	    if(retval == EOF){ /* This shouldn't occur... */
	      fclose(fp_out);
	      fprintf(stderr,"[join_vtk_dump]: EOF returned for file \"%s\"\n",
		      domain_3d[k][j][i].fname);
	      return;
	    }

	    if(strcmp(type, t_type) != 0 ||
	       strcmp(variable, t_variable) != 0 ||
	       strcmp(format, t_format) != 0 ){
	      fclose(fp_out);
	      join_error("mismatch in input file positions\n");
	    }
	  }

	  if(strcmp(type, "SCALARS") == 0){
	    /* Read in the LOOKUP_TABLE (only default supported for now) */
	    fscanf(domain_3d[k][j][i].fp,"%s %s\n", t_type, t_format);
	    if(strcmp(t_type, "LOOKUP_TABLE") != 0 ||
	       strcmp(t_format, "default") != 0 ){
	      fclose(fp_out);
	      fprintf(stderr,"Expected \"LOOKUP_TABLE default\"\n");
	      join_error("Found \"%s %s\"\n",t_type,t_format);
	    }
	  }

	  /* Prevent leading data bytes that correspond to "white space"
	     from being consumed by the fscanf's above -- MNL 2/6/06 */
          assert(fseek(domain_3d[k][j][i].fp, -1, SEEK_CUR) == 0);
	  while (isspace(fgetc(domain_3d[k][j][i].fp)))
            assert(fseek(domain_3d[k][j][i].fp, -2, SEEK_CUR) == 0);
	  assert(fgetc(domain_3d[k][j][i].fp) == '\n');
	}
      }
    }

    printf("Reading: \"%s %s %s\"\n",type,variable,format);

    /* Now, every file should agree that we either have SCALARS or
       VECTORS data */
    fprintf(fp_out,"%s %s %s\n",type,variable,format);
    if(strcmp(type, "SCALARS") == 0){
      fprintf(fp_out,"LOOKUP_TABLE default\n");
      read_write_scalar(fp_out);
    }
    else if(strcmp(type, "VECTORS") == 0){
      read_write_vector(fp_out);
    }
    else
      join_error("Input type = \"%s\"\n",type);
  }

  return;
}
Esempio n. 26
0
static int process_resources(const char* input_file_name, const char* specific_file_name, 
		      int inserting, int force_processing, int verbose)
{
    char buffer[2048], tmp_file_name[PATH_MAX];
    const char *res_file_name;
    time_t rc_last_update, res_last_update;
    FILE *fin, *fres, *ftmp = 0;
    struct stat st;
    int fd, c;

    if (!(fin = fopen(input_file_name, "r"))) return 0;
    if (stat(input_file_name, &st) < 0) return 0;
    rc_last_update = st.st_mtime;

    if (inserting)
    {
	strcpy(tmp_file_name, input_file_name);
	strcat(tmp_file_name, "-XXXXXX.temp");
	if ((fd = mkstemps(tmp_file_name, 5)) == -1)
	{
	    strcpy(tmp_file_name, "/tmp/bin2res-XXXXXX.temp");
	    if ((fd = mkstemps(tmp_file_name, 5)) == -1) return 0;
	}
	clean_file = tmp_file_name;
	if (!(ftmp = fdopen(fd, "w"))) return 0;
    }

    for (c = EOF; fgets(buffer, sizeof(buffer), fin); c = EOF)
    {
	if (inserting) fprintf(ftmp, "%s", buffer);
	if (!(res_file_name = parse_marker(buffer, &res_last_update))) continue;
        if ( (specific_file_name && strcmp(specific_file_name, res_file_name)) ||
	     (!force_processing && ((rc_last_update < res_last_update) == !inserting)) )
        {
	    if (verbose) printf("skipping '%s'\n", res_file_name);
            continue;
        }

        if (verbose) printf("processing '%s'\n", res_file_name);
	while ( (c = fgetc(fin)) != EOF && c != '{')
	    if (inserting) fputc(c, ftmp);
	if (c == EOF) break;

	if (inserting)
	{
	    if (!(fres = fopen(res_file_name, "rb"))) break;
	    if (!insert_hexdump(ftmp, fres)) break;
	    while ( (c = fgetc(fin)) != EOF && c != '}') /**/;
	    fclose(fres);
	}
	else
	{
	    clean_file = res_file_name;
	    if (!(fres = fopen(res_file_name, "wb"))) break;
	    if (!extract_hexdump(fres, fin)) break;
	    fclose(fres);
	    clean_file = NULL;
	}
    }

    fclose(fin);

    if (inserting)
    {
	fclose(ftmp);
	if (c == EOF)
        {
            if (rename(tmp_file_name, input_file_name) < 0)
            {
                /* try unlinking first, Windows rename is brain-damaged */
                if (unlink(input_file_name) < 0 || rename(tmp_file_name, input_file_name) < 0)
                    return 0;
            }
            clean_file = NULL;
        }
    }

    return c == EOF;
}
Esempio n. 27
0
int main(int argc, const char* argv[]){
    const char *task=argv[1];
    const char *lang=argv[2];
    sandbox_t s;
    char prog[256];
    const char *c[3];
    long double ti;
    if(strcmp(lang,"cpp")*strcmp(lang,"c")*strcmp(lang,"python2")*strcmp(lang,"python3")==0){
        if(strcmp(lang,"cpp")*strcmp(lang,"c")==0){
            sprintf(prog,"./%s",task);
            c[0]=prog;
        } else if(strcmp(lang,"python2")==0){
            c[0]="/usr/bin/python2";
            c[1]=task;
        } else if(strcmp(lang,"python3")==0){
            c[0]="/usr/bin/python3";
            c[1]=task;
        }
        sandbox_init(&s,c);
        s.task.quota[S_QUOTA_WALLCLOCK]=REAL;
        s.task.quota[S_QUOTA_CPU]=CPU;
        s.task.quota[S_QUOTA_MEMORY]=MEM;
        s.task.quota[S_QUOTA_DISK]=DISK;
        s.task.uid=getuid();
        s.task.gid=getgid();
        char outf[250];
        sprintf(outf,"%s.out",task);
        FILE *ofp=fopen(outf,"w");
        s.task.ofd=fileno(ofp);
        char inf[250];
        sprintf(inf,"%s.in",task);
        FILE *ifp=fopen(inf,"r");
        s.task.ifd=fileno(ifp);
        FILE *efp=fopen("../stderr","w");
        s.task.efd=fileno(efp);
        result_t* r=sandbox_execute(&s);
        fclose(ifp);
        fclose(ofp);
        fclose(efp);
        stat_t st=s.stat;
        ti=st.cpu_info.clock.tv_sec+st.cpu_info.clock.tv_nsec/1.0e9;
        if(*r!=S_RESULT_OK){
            switch(*r){
                case S_RESULT_RF:
                    printf("Wrong: restricted function\n");
                    return 6;
                case S_RESULT_ML:
                    printf("Wrong: memory limit exceeded\n");
                    return 4;
                case S_RESULT_TL:
                    printf("Wrong: time limit exceeded\n");
                    return 3;
                case S_RESULT_RT:
                    printf("Wrong: runtime error\n");
                    return 5;
                case S_RESULT_AT:
                    printf("Wrong: abnormal termination\n");
                    return 5;
            }
        }
    } else if (strcmp(lang,"java")==0) {
        sprintf(prog,"ulimit -t 30;/usr/bin/java -Djava.security.manager -Djava.security.policy=../policy -Xmx%d -Xms%d %s < %s.in > %s.out",MEM,MEM,task,task,task);
        struct timeval start, end;
        gettimeofday(&start, NULL);
        system(prog);
        gettimeofday(&end, NULL);
        ti=(end.tv_sec-start.tv_sec)+(end.tv_usec - start.tv_usec)/1.0e6;
    }

    char resfile[256],corfile[256];
    strcpy(resfile,task);strcat(resfile,".out");
    strcpy(corfile,"../");strcat(corfile,resfile);

    FILE *cor=fopen(corfile,"r");

    bool good=true;
    FILE *res;
    if((res=fopen(resfile,"r"))!=NULL){
        while(!feof(cor)&&!feof(res)){
            if(fgetc(res)!=fgetc(cor)){
                good=false;
                break;
            }
        }
    } else
        good=false;
    if(good){
        
        printf("OK %Lf\n",ti);
        return 0; // correct
    } else {
        printf("Wrong: incorrect output\n");
        return 2; // wrong
    }
}
Esempio n. 28
0
int main(int argc, char* argv[])
{
    char c, prev;
    enum state {NORMAL, STRING, COMMENT, CHAR};
    int state = NORMAL;

    int stack[30];
    int pos = 0;

    if(argc != 2) {
        printf("./run file\n");
        exit(0);
    }

    FILE* file = fopen(argv[1], "r");

    while((c = fgetc(file)) != EOF) {
        if(state == NORMAL) {
            if(prev == '/' && c == '*') {
                state = COMMENT;
            } else if(c == '"') {
                state = STRING;
                printf("string\n");
            } else if(c == '\'') {
                state = CHAR;
            }

            prev = c;
            continue;
        } else if(state == STRING) {
            if(prev == '\\' && c == '\\') {
                prev = 0;
            } else if(c == '"') {
                if(prev != '\\') {
                    state = NORMAL;
                }
            }
        } else if(state == COMMENT) {
            if(prev == '*' && c == '/') {
                prev = 0;
                state = NORMAL;
            }
        } else if(state == CHAR) {
            if(prev == '\\' && c == '\\') {
                prev = 0;
            } else if(c == '\'' && prev != '\\') {
                state = NORMAL;
            }
        }

        prev = c;
    }

    fclose(file);

    if(state == STRING) {
        printf("Unterminated String\n");
    } else if(state == COMMENT) {
        printf("Unterminated String\n");
    }

    exit(0);
}
Esempio n. 29
0
int main()
{
  FILE *fp = fopen("test.txt", "r");
  int c = 0;
  int i = 0;
  char s[512];
  Table_T our_table = Table_new(10, NULL, NULL);
  char * name;
  const char *fingerprint;
  const char* temp;
  while((c=fgetc(fp)) != ' ' && c != EOF)  //Fingerprint section
    {
      s[i]= c;
      i++;
    }
  s[i] = '\0';
  //Here we have fingerprint in s
  fingerprint = Atom_string(s);
  temp = Atom_string(s); 
  i = 0;
  while((c = getc(fp)) != '\n' && c != EOF)
    {
      s[i] = c;
      i++;
    }
  s[i] = '\0';
  //Here we have name in s
  name = s;    
  Table_put(our_table, fingerprint, name);
  while( c != EOF)
    {
      i = 0;
      while((c = fgetc(fp)) != ' ' && c != EOF) // Fingerprint section
	{
	  s[i] = c;
          i++;
	}
       s[i] = '\0';
       fingerprint = Atom_string(s);
       i = 0;
       while((c = getc(fp)) != '\n' && c != EOF)
	   {
             s[i] = c;
             i++;
            }
        s[i] = '\0';
        name = s;
        printf("FP: %s\n ", fingerprint);
    printf("NAME: %s\n", name);
 
	char * test = Table_put(our_table, fingerprint, name);
        printf("idk: %s\n", test); 
	// printf("VALUE STORED IN FP: %s\n\n", (char *)Table_get(our_table, temp));   
  }

  // NEED TO DEAL WITH TABLE MAP AND IMPLEMENTING A LIST   
  // Table_map(our_table, vfree, NULL);
  
  //printf("%s", fingerprint);
  // printf("%s", (char *)Table_get(our_table, fingerprint));
  
  printf("%d", Table_length(our_table));
  
  // Table_map(our_table, vfree, NULL);
  int length = Table_length(our_table);
  void **table = Table_toArray(our_table, NULL);
 for(int x = 0; x < 2*length; x++)
    {
      printf("%s ", (char *)table[x]); 
   }


  Table_free(&our_table);
  return 0;
}
Esempio n. 30
0
/*
  Format of data: 8 hexadecimal numbers with spaces
*/
int dbus_decomp(const char *filename, int resync)
{
    char src_name[1024];
    char dst_name[1024];
    FILE *fi, *fo;
    long file_size;
    struct stat st;
    unsigned char *buffer;
    int i;
	unsigned int j;
    int num_bytes;
	char str[256];
	unsigned char mid, cid;
	unsigned int length;
	int idx;
	int ret = 0;
    
	// build filenames
    strcpy(src_name, filename);
    strcat(src_name, ".hex");
    
    strcpy(dst_name, filename);
    strcat(dst_name, ".pkt");
    
    stat(src_name, &st);
    file_size = st.st_size;
    
	// allocate buffer
    buffer = (unsigned char*)calloc(file_size/2, 1);
    memset(buffer, 0xff, file_size/2);
    if(buffer == NULL)
    {
        fprintf(stderr, "calloc error.\n");
        exit(-1);
    }
    
	// open files
    fi = fopen(src_name, "rt");
    fo = fopen(dst_name, "wt");
    
    if(fi == NULL)
    {
        fprintf(stderr, "Unable to open this file: %s\n", src_name);
        return -1;
    }

    fprintf(fo, "TI packet decompiler for D-BUS, version 1.2\n");

	// skip comments
	fgets(str, sizeof(str), fi);
	fgets(str, sizeof(str), fi);
	fgets(str, sizeof(str), fi);

	// read source file
	for(i = 0; !feof(fi);)
    {
        for(j = 0; j < 16 && !feof(fi); j++)
		{
			fscanf(fi, "%02X", &(buffer[i+j]));
			fgetc(fi);
		}
        i += j;

        for(j=0; j<18 && !feof(fi); j++)
			fgetc(fi);
    }
    num_bytes = i-1; // -1 due to EOF char
    fprintf(stdout, "%i bytes read.\n", num_bytes);

	// process data
	for(i = 0; i < num_bytes;)
    {
restart:
		mid = buffer[i+0];
		cid = buffer[i+1];
		length = buffer[i+2];
        length |= buffer[i+3] << 8;

		// check for valid packet
		if(is_a_machine_id(mid) == -1)
		{
			ret = -1;
			goto exit;
		}

		// check for valid packet
		idx = is_a_command_id(cid);
        if(idx == -1)
		{
			ret = -2;
			goto exit;
		}

		fprintf(fo, "%02X %02X %02X %02X", mid, cid, length >> 8, length & 0xff);
		for(j = 4; j <= WIDTH; j++)
			fprintf(fo, "   ");
		fprintf(fo, "  | ");
		fprintf(fo, "%s: %s\n", machine_way[is_a_machine_id(mid)], command_name[is_a_command_id(cid)]);

		i += 4;

		// get data & checksum
		if(cmd_with_data[idx] && length > 0)
		{
			// data
			for(j = 0; j < length; j++, i++)
			{
				if(resync && buffer[i] == 0x98 && (buffer[i+1] == 0x15 ||  buffer[i+1] == 0x56))
				{
					fprintf(stdout, "Warning: there is packets in data !\n");
					fprintf(fo, "Beware : length of previous packet is wrong !\n");
					goto restart;
				}

				fill_buf(fo, buffer[i], 0);
			}

			fill_buf(fo, 0, !0);
			//fprintf(fo, "\n");

			// write checksum
			fprintf(fo, "    ");
			fprintf(fo, "%02X ", buffer[i++]);
			fprintf(fo, "%02X ", buffer[i++]);
			fprintf(fo, "\n");
		}
	}

exit:
	if(ret < 0)
		fprintf(stdout, "Error %i\n", -ret);

	free(buffer);
	fclose(fi);
	fclose(fo);
    
	return ret;
}