Ejemplo n.º 1
0
int main(void)
{
	char buffer[3];
	int selection,done;
	done = 0;
	
	while (1)
	{
		printf("\n\n   **** Ballistic Calculator Menu ****\n\n");
		printf(" 1. Calculate Trajectory\n");
		printf(" 2. Calculate Ballistic Coefficient\n");
		printf(" 3. Calculate Distance to Target from Mil-Dots\n");
		printf(" 4. Calculate Optimum Twist Rate\n");
	
		printf("\n 99. Exit\n\n");
		printf("Enter Selection: ");
		
		sgets(buffer,sizeof buffer);
		selection = atoi(buffer);
		
		printf("\n\n");
		
		switch (selection)
		{
			case 1:
				trajectory();
				PauseForEnterKey();
				break;
				
			case 2:
				ballistic_coefficient();
				PauseForEnterKey();
				break;
				
			case 3:
				mildot();
				PauseForEnterKey();
				break;
			
			case 4:
				twist_rate();
				PauseForEnterKey();
				break;
					
			case 99:
				done = 1;
				break;
				
			default:
				printf("Invalid Entry\n");
				break;
		}
		if (done == 1) break;
	}
	return 0;
}
Ejemplo n.º 2
0
Archivo: ini.c Proyecto: sobomax/digger
void GetINIString(const char *section,const char*key,const char*def,char*dest,
                             int destsize,const char *filename)
{
  FILE *fp;
  char s1[80],s2[80],s3[80];
  /* FIXME: no sense in copying from to the same destination as source,
   * figure out what is really attempted here
   */
  if (dest != def)
    strcpy(dest,def);
  fp=fopen(filename,"rb");
  if (fp==NULL)
    return;
  strcpy(s2,"[");
  strcat(s2,section);
  strcat(s2,"]");
  strcpy(s3,key);
  strcat(s3,"=");
  do {
    if (fgets(s1, 80, fp) == NULL) {
      fprintf(stderr, "GetINIString: read failed: %s\n", filename);
      goto out_0;
    }
    sgets(s1,s1);
    if (stricmp(s1,s2)==0) {
      do {
        if (fgets(s1, 80, fp) == NULL) {
          fprintf(stderr, "GetINIString: read failed: %s\n", filename);
          goto out_0;
        }
        sgets(s1,s1);
        if (strnicmp(s1,s3,strlen(s3))==0) {
          strcpy(dest,s1+strlen(s3));
          goto out_0;
        }
      } while (s1[0]!=0 && !feof(fp) && !ferror(fp));
    }
  } while (!feof(fp) && !ferror(fp));
out_0:
  fclose(fp);
}
Ejemplo n.º 3
0
int twist_rate(void)
{
	char buffer[80];
	double tr,bl,v,d;
	
	printf("\n\n\t * Optimum Twist Rate * \n");
	
	while(1)
	{
		printf("\nBore Groove Diameter (in) : ");
		sgets(buffer,80);
		d = atof(buffer);
		if (d > 0) break;
		printf("Bore Groove Diameter must be > 0!\n");
	}
	
	while(1)
	{
		printf("\nBullet Length (in) : ");
		sgets(buffer,80);
		bl = atof(buffer);
		if (bl > 0) break;
		printf("Bullet Length must be > 0!\n");
	}
	
	while(1)
	{
		printf("\nBullet Velocity (fps) : ");
		sgets(buffer,80);
		v = atof(buffer);
		if (v > 0) break;
		printf("Bullet Velocity must be > 0!\n");
	}
	
	tr = (3.5 * sqrt(v) * d*d) / bl;
	
	printf("\n\nOptimum Twist Rate : 1 twist in %3.1f in\n",tr);
	
	return 0;

}
Ejemplo n.º 4
0
/**
 * sgets2:  Read a line of text from a socket, and strip newline and
 *          carriage return characters from the end of the line.
 * @param buf Buffer to get
 * @param len Length
 * @param s Socket
 * @return buffer
 */
char *sgets2(char *buf, int len, ano_socket_t s)
{
    char *str = sgets(buf, len, s);

    if (!str || str == (char *) -1)
        return str;
    str = buf + strlen(buf) - 1;
    if (*str == '\n')
        *str-- = 0;
    if (*str == '\r')
        *str = 0;
    return buf;
}
Ejemplo n.º 5
0
void GetINIString(char* section,char* key,char* def,char* dest,
                  int destsize,char* filename)
{
  FILE* fp;
  char s1[80],sectstr[80],keystr[80];
  char* src;
  int i;
  strcpy(dest,def);
  fp=fopen(filename,"rb");
  if (fp==NULL)
    return;
  strcpy(sectstr,"[");
  strcat(sectstr,section);
  strcat(sectstr,"]");
  strcpy(keystr,key);
  strcat(keystr,"=");
  do {
    fgets(s1,80,fp);
    sgets(s1,s1);
    if (_stricmp(s1,sectstr)==0) {
      do {
        fgets(s1,80,fp);
        sgets(s1,s1);
        if (_strnicmp(s1,keystr,strlen(keystr))==0) {
          src=s1+strlen(keystr);
          for (i=0;i<destsize-1 && src[i]!=0;++i)
            dest[i]=src[i];
          dest[i]=0;
          fclose(fp);
          return;
        }
      } while (s1[0]!=0 && !feof(fp) && !ferror(fp));
    }
  } while (!feof(fp) && !ferror(fp));
  fclose(fp);
}
Ejemplo n.º 6
0
/* Input a number as (at most 8) hex digits - returns value entered */
long hexIn(void)
{
	char input[40];
	long num;
	register int i;

	i = 0;
	num = 0;

	if (sgets (input))  /* grab a line */
	{
        num = hex2dec(input[i++]);       	/* Convert MSD to dec */
        while(ishex(input[i]) && input[i])  /* Get next hex digit */
	    {
            num <<= 4;						/* Make room for next digit */
            num += hex2dec(input[i++]); 	/* Add it in */
        }
	}
	return num;
}
Ejemplo n.º 7
0
void sqlite_api_query_cb(const char *input)
{
	const char *ptr = input;
	char query[4096];
	int ret;

	assert(input != NULL);

	if (input[0] == 0) {
		return;
	}

	while (sgets(query, sizeof(query), &ptr)) {
		ret = sqlite3_exec(meta_db, query, 0, 0, 0);
		if (ret != SQLITE_OK) {
			printf("Error executing query:\n%s\n", query);
			exit(1);
		}
	}
}
Ejemplo n.º 8
0
static int
gx_serialize_CIEICC(const gs_color_space * pcs, stream * s)
{
    const gs_icc_params * p = &pcs->params.icc;
    gs_cie_icc *picc = p->picc_info;
    uint n;
    int code = gx_serialize_cspace_type(pcs, s);
    long avail, pos, count;
    byte buf[100];

    if (code < 0)
	return code;
    code = gx_serialize_cie_common_elements(pcs, s);
    if (code < 0)
	return code;
    code = sputs(s, (byte *)&picc->num_components, sizeof(picc->num_components), &n);
    if (code < 0)
	return code;
    code = sputs(s, (byte *)&picc->Range, sizeof(picc->Range), &n);
    if (code < 0)
	return code;
    if (sseek(picc->instrp, 0) < 0)
	return_error(gs_error_unregistered); /* Unimplemented. */
    if (savailable(picc->instrp, &avail) != 0)
	return_error(gs_error_unregistered); /* Unimplemented. */
    code = sputs(s, (byte *)&avail, sizeof(avail), &n);
    if (code < 0)
	return code;
    for (pos = 0; pos < avail; pos += count) {
	count = min(sizeof(buf), avail - pos);
	code = sgets(picc->instrp, buf, count, &n);
	if (code < 0)
	    return code;
	code = sputs(s, buf, count, &n);
	if (code < 0)
	    return code;
    }
    return sputs(s, (byte *)&picc->pcs_is_cielab, sizeof(picc->pcs_is_cielab), &n);
}
Ejemplo n.º 9
0
/* Input a number as decimal digits - returns value entered */
long decIn(void)
{
    char input[40];
	int num;
	int tmp;
	register int i;

	i = 0;
	num = 0;

	if (sgets (input))  /* grab a line */
	{
        atod(input[i++], &num);      	/* Convert MSD to decimal */
        while(isdec(input[i]) && input[i])  /* Get next decimal digit */
	    {
            num *= 10;                 	/* Make room for next digit */
			atod(input[i++], &tmp);
            num += tmp; 			/* Add it in */
        }
	}

	return (num);
}
Ejemplo n.º 10
0
dictionary * iniparser_load(char * ininame, bool isbuffer)
{
    dictionary  *   d ;
    char        sec[ASCIILINESZ+1];
    char        lin[ASCIILINESZ+1];
    FILE    *   ini ;
    int         lineno ;
	memset(lin, 0, ASCIILINESZ);
	memset(sec, 0, ASCIILINESZ);

    if (!isbuffer && (ini=fopen(ininame, "r"))==NULL) {
        return NULL ;
    }

	if(isbuffer && !ininame) {
		return NULL ;
	}

    /*
     * Initialize a new dictionary entry
     */
    d = dictionary_new(0);
    lineno = 0 ;
	int pos = 0;
	while ((isbuffer ? sgets(ininame, &pos, lin, ASCIILINESZ) : fgets(lin, ASCIILINESZ, ini)) != NULL) {
		lineno++;
		parse_line(sec, lin, d);
		memset(lin, 0, ASCIILINESZ);
    }

	if(strlen(lin) != 0)
		parse_line(sec, lin, d);
    
	if(!isbuffer) fclose(ini);

    return d ;
}
Ejemplo n.º 11
0
/* Get bytes from GlyphData or DataSource. */
static int
cid0_read_bytes(gs_font_cid0 *pfont, ulong base, uint count, byte *buf,
                gs_glyph_data_t *pgd)
{
    const font_data *pfdata = pfont_data(pfont);
    byte *data = buf;
    gs_font *gdfont = 0;	/* pfont if newly allocated, 0 if not */
    int code = 0;

    /* Check for overflow. */
    if (base != (long)base || base > base + count)
        return_error(e_rangecheck);
    if (r_has_type(&pfdata->u.cid0.DataSource, t_null)) {
        /* Get the bytes from GlyphData (a string or array of strings). */
        const ref *pgdata = &pfdata->u.cid0.GlyphData;

        if (r_has_type(pgdata, t_string)) {  /* single string */
            uint size = r_size(pgdata);

            if (base >= size || count > size - base)
                return_error(e_rangecheck);
            data = pgdata->value.bytes + base;
        } else {		/* array of strings */
            /*
             * The algorithm is similar to the one in
             * string_array_access_proc in zfont42.c, but it also has to
             * deal with the case where the requested string crosses array
             * elements.
             */
            ulong skip = base;
            uint copied = 0;
            uint index = 0;
            ref rstr;
            uint size;

            for (;; skip -= size, ++index) {
                int code = array_get(pfont->memory, pgdata, index, &rstr);

                if (code < 0)
                    return code;
                if (!r_has_type(&rstr, t_string))
                    return_error(e_typecheck);
                size = r_size(&rstr);
                if (skip < size)
                    break;
            }
            size -= skip;
            if (count <= size) {
                data = rstr.value.bytes + skip;
            } else {		/* multiple strings needed */
                if (data == 0) {  /* no buffer provided */
                    data = gs_alloc_string(pfont->memory, count,
                                           "cid0_read_bytes");
                    if (data == 0)
                        return_error(e_VMerror);
                    gdfont = (gs_font *)pfont; /* newly allocated */
                }
                memcpy(data, rstr.value.bytes + skip, size);
                copied = size;
                while (copied < count) {
                    int code = array_get(pfont->memory, pgdata, ++index, &rstr);

                    if (code < 0)
                        goto err;
                    if (!r_has_type(&rstr, t_string)) {
                        code = gs_note_error(e_typecheck);
                        goto err;
                    }
                    size = r_size(&rstr);
                    if (size > count - copied)
                        size = count - copied;
                    memcpy(data + copied, rstr.value.bytes, size);
                    copied += size;
                }
            }
        }
    } else {
        /* Get the bytes from DataSource (a stream). */
        stream *s;
        uint nread;
        i_ctx_t *i_ctx_p = get_minst_from_memory(pfont->memory)->i_ctx_p;

        check_read_known_file(i_ctx_p, s, &pfdata->u.cid0.DataSource, return_error);
        if (sseek(s, base) < 0)
            return_error(e_ioerror);
        if (data == 0) {	/* no buffer provided */
            data = gs_alloc_string(pfont->memory, count, "cid0_read_bytes");
            if (data == 0)
                return_error(e_VMerror);
            gdfont = (gs_font *)pfont; /* newly allocated */
        }
        if (sgets(s, data, count, &nread) < 0 || nread != count) {
            code = gs_note_error(e_ioerror);
            goto err;
        }
    }
    gs_glyph_data_from_string(pgd, data, count, gdfont);
    return code;
 err:
    if (data != buf)
        gs_free_string(pfont->memory, data, count, "cid0_read_bytes");
    return code;
}
Ejemplo n.º 12
0
bool
OsdUtilSubdivTopology::ParseFromObjString(
    char const * shapestr, int axis,
    vector<float> *pointPositions,
    std::string *errorMessage)
{
    char * str=const_cast<char *>(shapestr), line[256];
    bool done = false;
    
    while( not done ) {
        
        done = sgets(line, sizeof(line), &str)==0;
        char* end = &line[strlen(line)-1];
        if (*end == '\n')
            *end = '\0'; // strip trailing nl
        
        float x, y, z, u, v;
        switch (line[0]) {
        case 'v': switch (line[1]) {
            case ' ':
                if(sscanf(line, "v %f %f %f", &x, &y, &z) == 3) {
                    pointPositions->push_back(x);
                    switch( axis ) {
                    case 0 : pointPositions->push_back(-z);
                        pointPositions->push_back(y); break;
                    case 1 : pointPositions->push_back(y);
                        pointPositions->push_back(z); break;
                    }
                } break;
            case 't':
                if(sscanf(line, "vt %f %f", &u, &v) == 2) {
                    //XXX:gelder
                    // extract UVs
                    // s->uvs.push_back(u);
                    // s->uvs.push_back(v);
                } break;
            case 'n' :
                break; // skip normals for now
            }
            break;
        case 'f':
            if(line[1] == ' ')  {
                int vi, ti, ni;
                const char* cp = &line[2];
                while (*cp == ' ') cp++;
                int numVerts = 0, nitems=0;
                while( (nitems=sscanf(cp, "%d/%d/%d", &vi, &ti, &ni))>0) {
                    numVerts++;
                    indices.push_back(vi-1);
                    //XXX:gelder
                    // Extract face varying uvs
                    //if(nitems >= 1) s->faceuvs.push_back(ti-1);
                    //if(nitems >= 2) s->facenormals.push_back(ni-1);
                    while (*cp && *cp != ' ') cp++;
                    while (*cp == ' ') cp++;
                }
                nverts.push_back(numVerts);
            }
            break;
//        case 't' : if(line[1] == ' ') {
//                shape::tag * t = tag::parseTag( line );
//                if (t)
//                    s->tags.push_back(t);
//            } break;
        }
    }

    numVertices = (int)pointPositions->size()/3;

    return true;
}
Ejemplo n.º 13
0
void WriteINIString(char *section,char *key,WCHAR *value,char *filename)
{
  FILE *fp;
  char *buffer,*p,*p0,s1[80],s2[80],s3[80];
  int tl;
  fp=fopen(filename,"rb");
  if (fp==NULL) {
    fp=fopen(filename,"wb");
    if (fp==NULL)
      return;
    fprintf(fp,"[%s]" NEWL,section);
    fprintf(fp,"%s=%s" NEWL NEWL,key,value);
    fclose(fp);
    return;
  }
  fseek(fp,0,2);
  tl=(int)ftell(fp);
  fseek(fp,0,0);
  buffer=(char *)malloc(tl+1);
  if (buffer==NULL) {
    fclose(fp);
    return;
  }
  fread(buffer,tl,1,fp);
  buffer[tl]=0;
  fclose(fp);
  strcpy(s2,"[");
  strcat(s2,section);
  strcat(s2,"]");
  strcpy(s3,key);
  strcat(s3,"=");
  p=buffer;
  do {
    p=sgets(p,s1);
    if (_stricmp(s1,s2)==0) {
      do {
        p0=p;
        p=sgets(p,s1);
        if (_strnicmp(s1,s3,strlen(s3))==0) {
          fp=fopen(filename,"wb");
          if (fp==NULL) {
            free(buffer);
            return;
          }
          fwrite(buffer,p0-buffer,1,fp);
          fprintf(fp,"%s=%s" NEWL,key,value);
          fwrite(p,tl-(p-buffer),1,fp);
          fclose(fp);
          free(buffer);
          return;
        }
      } while (s1[0]!=0);
      fp=fopen(filename,"wb");
      if (fp==NULL) {
        free(buffer);
        return;
      }
      fwrite(buffer,p0-buffer,1,fp);
      fprintf(fp,"%s=%s" NEWL,key,value);
      fwrite(p0,tl-(p0-buffer),1,fp);
      fclose(fp);
      free(buffer);
      return;
    }
  } while (p<buffer+tl);
  fp=fopen(filename,"wb");
  if (fp==NULL) {
    free(buffer);
    return;
  }
  fprintf(fp,"[%s]" NEWL,section);
  fprintf(fp,"%s=%s" NEWL NEWL,key,value);
  fwrite(buffer,tl,1,fp);
  fclose(fp);
  free(buffer);
  return;
}
Ejemplo n.º 14
0
int ballistic_coefficient(void)
{
	char buffer[80];
	double dc,iv,at,tp,bp,rh,tv;
	double drv,drd;
	double guess_current,guess_high,guess_low;
	int atm,df;
	double* sln=NULL;
	
	printf("\n\n\t * Ballistic Coefficient Calculator * \n");
	
	while(1)
	{
		printf("\nEnter Muzzle Velocity (ft/s) : ");
		sgets(buffer,80);
		iv = atof(buffer);
		if (iv > 0) break;
		printf("Muzzle Velocity must be > 0!\n");
	}
	
	while(1)
	{
		printf("\nEnter Down Range Velocity (ft/s) : ");
		sgets(buffer,80);
		drv = atof(buffer);
		if (drv > 0 || drv < iv) break;
		printf("Down Range Velocity must be > 0 and < Muzzle Velocity!\n");
	}
	
	while(1)
	{
		printf("\nEnter Down Range Distance (yds) : ");
		sgets(buffer,80);
		drd = atof(buffer);
		if (drd > 0) break;
		printf("Down Range Distance must be > 0!\n");
	}
	
	while(1)
	{
		printf("\n");
		printf("G0 Roundball\n");
		printf("G1 Ingalls (by far the most popular)\n");
		printf("G2 (Aberdeen J projectile)\n");
		printf("G5 (short 7.5deg boat-tail, 6.19 calibers long tangent ogive)\n");
		printf("G6 (flatbase, 6 calibers long secant ogive)\n");
		printf("G7 (long 7.5deg boat-tail, 10 calibers tangent ogive)\n");
		printf("G8 (flatbase, 10 calibers long secant ogive)\n");
		
		
		printf("\nEnter Drag Model 0,1,2,5,6,7 or 8 : ");
		sgets(buffer,80);
		df = atoi(buffer);
		if (df == 0) break;
		if (df == 1) break;
		if (df == 2) break;
		if (df == 5) break;
		if (df == 6) break;
		if (df == 7) break;
		if (df == 8) break;
		printf("Drag Model must be 0,1,2,5,6,7 or 8!\n");
	}
	
	atm = 0;
	
	printf("\nCorrect for Atmospheric Conditions (Y/N) : ");
	sgets(buffer,80);
	if (buffer[0] == 'Y' || buffer[0] == 'y')
	{
		atm = 1;
		while(1)
		{
			printf("\nEnter Altitude (ft) : ");
			sgets(buffer,80);
			at = atof(buffer);
			if (at >= 0) break;
			printf("Altitude must be >= 0!\n");
		}

		while(1)
		{
			printf("\nEnter Temperature (F) : ");
			sgets(buffer,80);
			tp = atof(buffer);
			if (tp > -100) break;
			printf("Temperature must be > -100 deg!\n");
		}

		while(1)
		{
			printf("\nEnter Barometric Pressure (in Hg) : ");
			sgets(buffer,80);
			bp = atof(buffer);
			if (bp > 20 && bp < 35) break;
			printf("Barometric Pressure must be > 20 and < 35!\n");
		}

		while(1)
		{
			printf("\nEnter Relative Humidity (%%) : ");
			sgets(buffer,80);
			rh = atof(buffer)/100;
			if (rh >= 0 && rh <= 100) break;
			printf("Relative Humidity must be between 0 and 100%%!\n");
		}
	}
	
	guess_current = 0.5;
	guess_low = 0.0;
	guess_high = 2.0;
		
	while(1)
	{
		dc = guess_current;
		
		if (atm == 1) dc = AtmCorrect(dc, at, bp, tp, rh);
		
		sln=NULL;
		
		SolveAll(df,dc, iv, 0, 0, 0, 0, 0, &sln);
		tv = GetVelocity(sln,drd);
				
		if (fabs(tv-drv) < 2) break;
		
		if (tv > drv)
		{
			guess_high = guess_current;
			guess_current = (guess_current + guess_low) / 2;
		}
		else
		{
			guess_low = guess_current;
			guess_current = (guess_current + guess_high) / 2;
		}
	}
	printf("\n\n G%d BC = %3.3f\n\n",df,guess_current);
	return 0;		
}
Ejemplo n.º 15
0
int read_header(int sid)
{
	char line[2048];
	char *pTemp;
	time_t x;

	strncpy(conn[sid].dat->in_RemoteAddr, inet_ntoa(conn[sid].ClientAddr.sin_addr), sizeof(conn[sid].dat->in_RemoteAddr)-1);
	x=time((time_t*)0);
	do {
		memset(line, 0, sizeof(line));
		sgets(line, sizeof(line)-1, conn[sid].socket);
		striprn(line);
	} while ((strlen(line)==0)&&((time((time_t)0)-x)<30));
	if ((strlen(line)==0)&&((time((time_t)0)-x)>=30)) {
#ifdef DEBUG
logdata("\n[[[ KILLING IDLE KEEPALIVE ]]]\n");
#endif
		closeconnect(sid, 1);
	}
#ifdef DEBUG
logdata("\n[[[ STARTING REQUEST ]]]\n");
#endif
	if (strlen(line)==0)
		printerror(sid, 400, "Bad Request", "No Request Found.");
	if (sscanf(line, "%[^ ] %[^ ] %[^ ]", conn[sid].dat->in_RequestMethod, conn[sid].dat->in_RequestURI, conn[sid].dat->in_Protocol)!=3)
		printerror(sid, 400, "Bad Request", "Can't Parse Request.");
	pTemp=conn[sid].dat->in_RequestMethod;
	while (*pTemp) { *pTemp=toupper(*pTemp); pTemp++; };
	while (strlen(line)>0) {
		sgets(line, sizeof(line)-1, conn[sid].socket);
		while ((line[strlen(line)-1]=='\n')||(line[strlen(line)-1]=='\r')) line[strlen(line)-1]='\0';
		if (strncasecmp(line, "Connection: ", 12)==0)
			strncpy(conn[sid].dat->in_Connection, (char *)&line+12, sizeof(conn[sid].dat->in_Connection)-1);
		if (strncasecmp(line, "Content-Length: ", 16)==0) {
			conn[sid].dat->in_ContentLength=atoi((char *)&line+16);
			if (conn[sid].dat->in_ContentLength<0) {
				// Negative Content-Length?  If so, the client is either broken or malicious.
				// Thanks to <*****@*****.**> for spotting this one.
				logerror("ERROR: negative Content-Length of %d provided by client.", conn[sid].dat->in_ContentLength);
				conn[sid].dat->in_ContentLength=0;
			}
		}
		if (strncasecmp(line, "Cookie: ", 8)==0)
			strncpy(conn[sid].dat->in_Cookie, (char *)&line+8, sizeof(conn[sid].dat->in_Cookie)-1);
		if (strncasecmp(line, "Host: ", 6)==0)
			strncpy(conn[sid].dat->in_Host, (char *)&line+6, sizeof(conn[sid].dat->in_Host)-1);
		if (strncasecmp(line, "If-Modified-Since: ", 19)==0)
			strncpy(conn[sid].dat->in_IfModifiedSince, (char *)&line+19, sizeof(conn[sid].dat->in_IfModifiedSince)-1);
		if (strncasecmp(line, "User-Agent: ", 12)==0)
			strncpy(conn[sid].dat->in_UserAgent, (char *)&line+12, sizeof(conn[sid].dat->in_UserAgent)-1);
	}
	if ((strcmp(conn[sid].dat->in_RequestMethod, "GET")!=0)&&(strcmp(conn[sid].dat->in_RequestMethod, "POST")!=0)) {
		printerror(sid, 501, "Not Implemented", "That method is not implemented.");
		closeconnect(sid, 1);
		return -1;
	}
	if (strcmp(conn[sid].dat->in_RequestMethod, "POST")==0) {
		if (conn[sid].dat->in_ContentLength<MAX_POSTSIZE) {
			ReadPOSTData(sid);
		} else {
			// try to print an error : note the inbuffer being full may block us
			// FIXME: this is causing the children to segfault in win32
			printerror(sid, 413, "Bad Request", "Request entity too large.");
			logerror("%s - Large POST (>%d bytes) disallowed", conn[sid].dat->in_RemoteAddr, MAX_POSTSIZE);
			closeconnect(sid, 1);
			return -1;
		}
	}
	if (conn[sid].dat->in_RequestURI[0]!='/') {
		printerror(sid, 400, "Bad Request", "Bad filename.");
	}
	if (strchr(conn[sid].dat->in_RequestURI, '?')!=NULL) {
		strncpy(conn[sid].dat->in_QueryString, strchr(conn[sid].dat->in_RequestURI, '?')+1, sizeof(conn[sid].dat->in_QueryString)-1);
	}
	return 0;
}
Ejemplo n.º 16
0
//
//	Internal version of getreply(), takes additional flags
//	(Used in ftp_recursive.c)
//
//	Get reply to an FTP command
//	This version works properly with multi-line replies
//
//	Results:
//		Success:	Returns the reply code from the ftp server - for multi-line
//			replies, this will be the code from the last line
//		Failure:	600 = Error, 700 = Break, 800 = Timeout
//
//		421 "Service not available, remote server has closed connection"
//		 is now returned for any error as in berkley ftp code
//
//	What do we do in situation for Timeout on read? AD simply calls this
//	an error and reports 421 which closes connection.
//	Should this not handle this and maybe just ignore it or resend command?
//
int _getreply(
	struct ftp_info  *info,
	unsigned long     flags,
	int             (*updatefn)(void *,int,char *),
	void             *updateinfo )
{
struct opusftp_globals *ogp = info->fi_og;
int   actual;			// Bytes received
int   first = 1;		// Is this the first line?
int   multi = 0;		// Multi-line reply
int   currcode;			// Current line's code
int   checkabort_time = 0;	// By default don't check for aborts on replies
char *iobuf;

// Need to allocate buffer for quiet io?
if	(flags & GETREPLY_QUIET)
	{
	if	(!(iobuf = AllocVec( IOBUFSIZE+1, MEMF_CLEAR )))
		{
		info->fi_reply = 600;
		return info->fi_reply;
		}
	}
else
	iobuf = info->fi_iobuf;

if	(info->fi_reply < 0) 	// not accept timeouts
	{
	checkabort_time = 1;

	// -2 is special marker for DEST STOR to return often to update progress bar
	if	(info->fi_reply == -2)
		checkabort_time = 2; 

	}
else
	info->fi_reply = 600;	// Error by default 
	
// Safety
flush_socket_buffer( info );

// Read one line at a time
do
	{
	// EOF or error
	if	((sgets( info, iobuf, IOBUFSIZE, info->fi_cs, checkabort_time )) == 0)
		{
		if	(info->fi_reply == 800)
			info->fi_errno = FTPERR_TIMEOUT;
		else
			info->fi_errno = FTPERR_FAKE_421;

		if	(info->fi_reply < 700)
			info->fi_reply = 600;

		break;
		}

	actual = strlen(iobuf);

	// NULL terminate
	iobuf[actual] = 0;

	// Got at least reply code?
	if	(actual >= 3
		&& isdigit( iobuf[0] )
		&& isdigit( iobuf[1] )
		&& isdigit( iobuf[2] ))
		currcode = iobuf[0] * 100 + iobuf[1] * 10 + iobuf[2] - '0' * 111;
	else
		currcode = 0;

	// Output reply, omitting the code if debug is off
	// No output if doing_noop
	if	(!info->fi_doing_noop)
		{
		if	(!ogp->og_oc.oc_log_debug && currcode)
			{
			if	(updatefn && updateinfo)
				(*updatefn)( updateinfo, -1, iobuf + 4 );

			logprintf( iobuf + 4 );
			}
		else
			{
			if	(updatefn && updateinfo)
				(*updatefn)( updateinfo, -1, iobuf );

			logprintf( iobuf );
			}
		}

	if	(currcode)
		{
		// Invalid code on any line ?
		if	(currcode < 100 || currcode > 559)
			{
			info->fi_reply = 600;
			break;
			}

		// Code is okay so update it
		info->fi_reply = currcode;

		// Start of multi-line reply?
		if	(iobuf[3] == '-')
			{
			if	(!multi)
				multi = 1;
			}
		// End of multi-line reply?
		else if	(multi)
			multi = 0;
		}

	// First block?
	if	(first)
		first = 0;

	// Mangled code on last line of reply
	if	(!multi && !currcode)
		{
		info->fi_reply = 600;
		break;
		}

	} while (multi);

// Convert ERROR codes to 'connection lost' code
if	(info->fi_reply >= 600)
	info->fi_reply = 421;

// Need to free buffer for quiet io?
if	(flags & GETREPLY_QUIET)
	if	(iobuf)
		FreeVec( iobuf );

return info->fi_reply;
}
Ejemplo n.º 17
0
int trajectory (void)
{
	char buffer[80];
	
	double dc,pw,iv,zr,sh,sa,wv,wa,at,tp,bp,rh,za,tv,cl=0.0,vcl,hcl,vd;
	double vmoa,vmils,hmoa,hmils;
	int md,mr,df,yi,x;
	double* sln=NULL;
	int spbr[5];
	int scope;
	
	printf("\n\n\t * Trajectory Calculator * \n");
	
	while(1)
	{
		printf("\nEnter Ballistic Coefficient : ");
		sgets(buffer,80);
		dc = atof(buffer);
		if (dc > 0 && dc < 2) break;
		printf("Ballistic Coefficient must > 0 and < 2!\n");
	}
	
	while(1)
	{
		printf("\n");
		printf("G0 Roundball\n");
		printf("G1 Ingalls (by far the most popular)\n");
		printf("G2 (Aberdeen J projectile)\n");
		printf("G5 (short 7.5deg boat-tail, 6.19 calibers long tangent ogive)\n");
		printf("G6 (flatbase, 6 calibers long secant ogive)\n");
		printf("G7 (long 7.5deg boat-tail, 10 calibers tangent ogive)\n");
		printf("G8 (flatbase, 10 calibers long secant ogive)\n");
		
		
		printf("\nEnter Drag Model 0,1,2,5,6,7 or 8 : ");
		sgets(buffer,80);
		df = atoi(buffer);
		if (df == 0) break;
		if (df == 1) break;
		if (df == 2) break;
		if (df == 5) break;
		if (df == 6) break;
		if (df == 7) break;
		if (df == 8) break;
		printf("Drag Model must be 0,1,2,5,6,7 or 8!\n");
	}
		
	while(1)
	{
		printf("\nEnter Bullet Weight (gr) : ");
		sgets(buffer,80);
		pw = atof(buffer);
		if (pw >= 1) break;
		printf("Bullet Weight must be >= 1 grain!\n");
	}
	
	while(1)
	{
		printf("\nEnter Muzzle Velocity (ft/s) : ");
		sgets(buffer,80);
		iv = atof(buffer);
		if (iv > 0) break;
		printf("Muzzle Velocity must be > 0!\n");
	}
	
	while(1)
	{
		printf("\nEnter Zero Range (yds) : ");
		sgets(buffer,80);
		zr = atof(buffer);
		if (zr >= 1) break;
		printf("Zero Range must be >= 1 yard!\n");
	}
	
	while(1)
	{
		printf("\nEnter Sight Height Above Bore (in) : ");
		sgets(buffer,80);
		sh = atof(buffer);
		if (sh > 0) break;
		printf("Sight Height must be > 0!\n");
	}

	while(1)
	{
		printf("\nEnter Shooting Angle (deg)  ");
		printf("\n\t+90\n");
		printf("\t 0 \n");
		printf("\t-90\n :");
		sgets(buffer,80);
		sa = atof(buffer);
		if (sa >= -90 && sa <= 90) break;
		printf("Shooting Angle must be between -90 and +90!\n");
	}
	
	while(1)
	{
		printf("\nEnter Wind Velocity (mph) : ");
		sgets(buffer,80);
		wv = atof(buffer);
		if (wv >= 0) break;
		printf("Wind Velocity cannot be < 0!\n");
	}
	
	while(1)
	{
		printf("\nEnter Wind Angle is Coming From (0-360 deg)");
		printf("\n\t 0\n");
		printf("270\t\t90\n");
		printf("\t180\n :");
		sgets(buffer,80);
		wa = atof(buffer);
		if (wa >= 0 && wa <= 360) break;
		printf("Wind Angle must be between 0 and 360 deg!\n");
	}

	printf("\nScope (Y/N) : ");
	sgets(buffer,80);
	scope = 0;
	if (buffer[0] == 'Y' || buffer[0] == 'y')
	{
		while(1)
		{	
			printf("\nEnter # Clicks to Move Scope 1 inch @ 100 yrds : ");
			sgets(buffer,80);
			cl = atof(buffer);
			if (cl >= 0) break;
			printf("# Clicks must not be < 0!\n");
		}
		scope = 1;	
	}

	while(1)
	{
		printf("\nEnter Vitals Diameter (in): ");
		sgets(buffer,80);
		vd = atof(buffer);
		if (vd >= 1) break;
		printf("Vitals Diameter must be at least 1 inch!\n");
	}
		
	printf("\nCorrect for Atmospheric Conditions (Y/N) : ");
	sgets(buffer,80);
	if (buffer[0] == 'Y' || buffer[0] == 'y')
	{
		while(1)
		{
			printf("\nEnter Altitude (ft) : ");
			sgets(buffer,80);
			at = atof(buffer);
			if (at >= 0) break;
			printf("Altitude must be >= 0!\n");
		}

		while(1)
		{
			printf("\nEnter Temperature (F) : ");
			sgets(buffer,80);
			tp = atof(buffer);
			if (tp > -100) break;
			printf("Temperature must be > -100 deg!\n");
		}

		while(1)
		{
			printf("\nEnter Barometric Pressure (in Hg) : ");
			sgets(buffer,80);
			bp = atof(buffer);
			if (bp > 20 && bp < 35) break;
			printf("Barometric Pressure must be > 20 and < 35!\n");
		}

		while(1)
		{
			printf("\nEnter Relative Humidity (%%) : ");
			sgets(buffer,80);
			rh = atof(buffer)/100;
			if (rh >= 0 && rh <= 100) break;
			printf("Relative Humidity must be between 0 and 100%%!\n");
		}
		
		dc = AtmCorrect(dc, at, bp, tp, rh);
	}
	
	za = ZeroAngle(df, dc, iv, sh, zr, 0.0);
		
	md = SolveAll(df, dc, iv, sh, sa, za, wv, wa, &sln);
	
	while(1)
	{
		printf("\nEnter Maximum Range (yds) up to %d yds for Table : ",md);
		sgets(buffer,80);
		mr = atoi(buffer);
		if (mr > 0 && mr < md) break;
		printf("Maximum Table Range must be > 0 and < %d yds!\n",md);
	}
	
	while(1)
	{
		printf("\nEnter Yardage Increment (yds) for Table : ");
		sgets(buffer,80);
		yi = atoi(buffer);
		if (yi >= 1 && yi < md) break;
		printf("Yardage Increment must be between 1 and %d yds!\n",md);
	}
	
	pbr(df, dc, iv, sh, vd, zr, spbr);
	
	printf("\n\n\t * Ballistic Information * \n");
	printf("\nFinal Ballistic Coefficient: %3.3f\n", dc);
	printf("Ballistic Model: G%d\n",df);
	printf("Muzzle Velocity: %3.0f fps\n",iv);
	printf("Muzzle Energy: %3.0f ft/lb\n",(pw * iv * iv)/450436);
	printf("Absolute Maximum Range: %d yds\n",md);
	printf("Zero Range: %3.0f yds\n",zr);
	printf("Shooting Angle: %3.1f deg\n",sa);
	if (spbr[4]/100.0 >= 0)
		printf("\n\nPBR Sight in for %3.0f yds: %3.1f in high\n",zr,fabs(spbr[4]/100.0));
	else
		printf("\n\nPBR Sight in for %3.0f yds: %3.1f in low\n",zr,fabs(spbr[4]/100.0));
	printf("\tPBR Vital Area Diameter: %3.1f in\n",vd);
	printf("\tPBR Near Zero: %d yds\n",spbr[0]);
	printf("\tPBR Far Zero: %d yds\n", spbr[1]);
	printf("\tMinimum PBR: %d yds\n",spbr[2]);
	printf("\tMaximum PBR: %d yds\n",spbr[3]);
	printf("\n\nWind Speed %3.1f mph from %3.1f deg\n",wv,wa);
	
	
	printf("\n\n\t * Flight Characteristics *\n");
	printf("\n\nDIST\tBD\tWind\tV\tE\tT\n");
	printf("(yds)\t(in)\t(in)\t(ft/s)\t(ft/lb)\t(sec)\n");
	for (x=yi;x<=mr;x+=yi)
	{
		printf("%d\t",x);
		printf("%3.1f\t",GetPath(sln,x));
		printf("%3.1f\t",GetWindage(sln,x));
		tv = GetVelocity(sln,x);
		printf("%3.0f\t",tv);
		printf("%3.0f\t",(pw * tv * tv)/450436);
		printf("%3.2f\n",GetTime(sln,x));
	} 
	printf("\n\n\n");
	if (scope)
	{
		printf("\t * Scope Adjustments *\n");
		printf("\n\nDIST\tVMOA\tVCLKS\tVMILS\tHMOA\tHCLKS\tHMILS\n");
	
		for (x=yi;x<=mr;x+=yi)
		{
			vcl=GetMOA(sln,x)*cl;
			hcl=GetWindageMOA(sln,x)*cl;
			vmoa = GetMOA(sln,x);
			vmils = GetMOA(sln,x)*0.2908;
			hmoa = GetWindageMOA(sln,x);
			hmils = GetWindageMOA(sln,x)*0.2908;
		
			printf("%d\t",x);
			if (vmoa > 0)
				printf("U%3.1f\t",vmoa);
			else
				printf("D%3.1f\t",fabs(vmoa));
				
			if (vcl > 0)
				printf("U%3.0f\t",vcl);
			else
				printf("D%3.0f\t",fabs(vcl));
			
			if (vmils > 0)
				printf("U%3.1f\t",vmils);
			else
				printf("D%3.1f\t",fabs(vmils));
			
			if (hmoa > 0)
				printf("R%3.1f\t",hmoa);
			else
				printf("L%3.1f\t",fabs(hmoa));
			
			if (hcl > 0)
				printf("R%3.0f\t",hcl);
			else
				printf("L%3.0f\t",fabs(hcl));
			
			if (hmils > 0)	
				printf("R%3.1f\t",hmils);
			else
				printf("L%3.1f\t",fabs(hmils));
			printf("\n");
		}
	}	 
	
	return 0;
}
Ejemplo n.º 18
0
/*
 * Read generic pixel image parameters.
 */
int
gx_pixel_image_sget(gs_pixel_image_t *pim, stream *s,
		    gs_color_space *pcs)
{
    uint control;
    float decode_default_1 = 1;
    int num_components, num_decode;
    int i;
    int code;
    uint ignore;

    if ((code = sget_variable_uint(s, &control)) < 0 ||
	(code = sget_variable_uint(s, (uint *)&pim->Width)) < 0 ||
	(code = sget_variable_uint(s, (uint *)&pim->Height)) < 0
	)
	return code;
    if_debug3('b', "[b]get control=0x%x, Width=%d, Height=%d\n",
	      control, pim->Width, pim->Height);
    if (control & PI_ImageMatrix) {
	if ((code = sget_matrix(s, &pim->ImageMatrix)) < 0)
	    return code;
	debug_b_print_matrix(pim);
    } else
	gx_image_matrix_set_default((gs_data_image_t *)pim);
    pim->BitsPerComponent = ((control >> PI_BPC_SHIFT) & PI_BPC_MASK) + 1;
    pim->format = (control >> PI_FORMAT_SHIFT) & PI_FORMAT_MASK;
    pim->ColorSpace = pcs;
    num_components = gs_color_space_num_components(pcs);
    num_decode = num_components * 2;
    if (gs_color_space_get_index(pcs) == gs_color_space_index_Indexed)
	decode_default_1 = (float)pcs->params.indexed.hival;
    if (control & PI_Decode) {
	uint dflags = 0x10000;
	float *dp = pim->Decode;

	for (i = 0; i < num_decode; i += 2, dp += 2, dflags <<= 2) {
	    if (dflags >= 0x10000) {
		dflags = sgetc(s) + 0x100;
		if (dflags < 0x100)
		    return_error(gs_error_ioerror);
	    }
	    switch (dflags & 0xc0) {
	    case 0x00:
		dp[0] = 0, dp[1] = DECODE_DEFAULT(i + 1, decode_default_1);
		break;
	    case 0x40:
		dp[0] = DECODE_DEFAULT(i + 1, decode_default_1), dp[1] = 0;
		break;
	    case 0x80:
		dp[0] = 0;
		if (sgets(s, (byte *)(dp + 1), sizeof(float), &ignore) < 0)
		    return_error(gs_error_ioerror);
		break;
	    case 0xc0:
		if (sgets(s, (byte *)dp, sizeof(float) * 2, &ignore) < 0)
		    return_error(gs_error_ioerror);
		break;
	    }
	}
	debug_b_print_decode(pim, num_decode);
    } else {
        for (i = 0; i < num_decode; ++i)
	    pim->Decode[i] = DECODE_DEFAULT(i, decode_default_1);
    }
    pim->Interpolate = (control & PI_Interpolate) != 0;
    pim->CombineWithColor = (control & PI_CombineWithColor) != 0;
    return control >> PI_BITS;
}
Ejemplo n.º 19
0
/*****************************************************************************
*
* flash_test - System Flash ROM diagnostics
*
* A destructive Flash ROM Read/Write test.  Note that the area of Flash
* which is tested changes based on whether the diagnostic is being invoked
* from the System code or from the Factory code (can't write over MON960).
*
* This test basically does a Longword Address test to the Flash area.
*
*/
void flash_test(MENU_ARG arg)
{

    ADDR start_addr = (ADDR)FLASH_ADDR;	/* Original */

    int i;
    unsigned long *f_ptr = (unsigned long *)FLASH_ADDR;
    int bytes_written = 0;
    unsigned long flash_data;
    char answer[20];

/* 10/31/00 */
    int status;

    init_eeprom();

    printf("***********************************\n");
    printf("***           WARNING           ***\n");
    printf("*** This test is destructive to ***\n");
    printf("*** all contents of the FLASH!  ***\n");
    printf("***********************************\n");

    printf("\nDo you wish to continue? (y/n)\n");
    sgets(answer);
    printf("\n\n");
    if ((answer[0] != 'y') && (answer[0] != 'Y'))
	return; 

    printf ("FLASH begins at 0x%X\n", FLASH_ADDR);
    printf ("Total FLASH size = 0x%X\n\n", eeprom_size);
    printf ("Checking FLASH ...\n");
    if (check_eeprom(NO_ADDR, 0) == OK)
        printf("FLASH is erased\n\n");
    else
        printf("FLASH is programmed between 0x%X and 0x%X\n\n",
                eeprom_prog_first, eeprom_prog_last);

    printf ("\nClearing Block Lock Bits... \n");
    if(clear_all_lock_bits(NO_ADDR)==OK)
        printf("Done!\n\n");
    else
        printf("Error!\n\n");
	
    printf ("Erasing FLASH...\n");
    if (erase_eeprom(NO_ADDR, 0) != OK)
        printf("Error on erase_eeprom()\n\n");
    else
        printf("Done Erasing FLASH!\n\n");
 
    (ADDR)start_addr = (ADDR)FLASH_BLK4_BASE_ADDR;

    printf ("Writing Longword Data to FLASH...\n");
 
    /* write to all of available Flash ROM.  Don't do this thousands of times
       since the Flash has only 100,000 write cycles in its lifespan */

    while (bytes_written < (eeprom_size - RESERVED_AREA_SIZE)) {
	flash_data = (unsigned long)start_addr;
    	for (i=0; i<TEST_BUF_LONGS; i++) {
            flash_buffer[i] = flash_data;	/* put address in buffer */
	    flash_data += 4;			/* increment address     */
	}
        if (write_eeprom (start_addr, (void *)flash_buffer, TEST_BUF_CHARS) != OK) {
            printf("Error on write_eeprom()\n");
            goto finish;
        }
        start_addr = (unsigned long)start_addr + TEST_BUF_CHARS;
        bytes_written += TEST_BUF_CHARS;
    }

    printf ("Write Complete, Verifying Data...\n");
    bytes_written = 0;
 
    f_ptr = (unsigned long *)FLASH_BLK4_BASE_ADDR;
    
    while (bytes_written < (eeprom_size - RESERVED_AREA_SIZE)) {
        if (*f_ptr != (unsigned long)f_ptr) {
            printf ("Data verification error at 0x%X\n", (unsigned long)f_ptr);
            printf ("Expected 0x%X Got 0x%X\n", (unsigned long)f_ptr, *f_ptr);
            goto finish;
        }
        f_ptr++;
        bytes_written += 4;
    }
    printf ("Done Verifying Longword Data!\n\n");

    printf ("Checking FLASH...\n");
    if (check_eeprom(NO_ADDR, 0) == OK)
        printf("FLASH is erased\n\n");
    else
        printf("FLASH is programmed between 0x%X and 0x%X\n\n",
                eeprom_prog_first, eeprom_prog_last);

    printf ("Erasing FLASH...\n");
    if (erase_eeprom(NO_ADDR, 0) != OK)
        printf("Error on erase_eeprom()\n\n");
    else
        printf("Done Erasing FLASH!\n\n");

    printf ("Checking FLASH...\n");
    if (check_eeprom(NO_ADDR, 0) == OK)
        printf("FLASH is erased\n\n");
    else
        printf("FLASH is programmed between 0x%X and 0x%X\n\n",
	       eeprom_prog_first, eeprom_prog_last);

    /* reinitialize variables */
    bytes_written = 0;
 
    start_addr = (ADDR)FLASH_BLK4_BASE_ADDR;
    f_ptr = (unsigned long *)FLASH_BLK4_BASE_ADDR;

    printf ("Writing Inverted Longword Data to FLASH...\n");
 
    /* write to all of available Flash ROM.  Don't do this thousands of times
       since the Flash has only 100,000 write cycles in its lifespan */

    while (bytes_written < (eeprom_size - RESERVED_AREA_SIZE)) {
	flash_data = (unsigned long)start_addr;
    	for (i=0; i<TEST_BUF_LONGS; i++) {
            flash_buffer[i] = ~flash_data;	/* put address BAR in buffer */
	    flash_data += 4;			/* increment address     */
	}
        if (write_eeprom (start_addr, (void *)flash_buffer, TEST_BUF_CHARS) != OK) {
            printf("Error on write_eeprom()\n");
            goto finish;
        }
        start_addr = (unsigned long)start_addr + TEST_BUF_CHARS;
        bytes_written += TEST_BUF_CHARS;
    }
 
    printf ("Write Complete, Verifying Data...\n");
    bytes_written = 0;
 
    while (bytes_written < (eeprom_size - RESERVED_AREA_SIZE)) {
        if (*f_ptr != (~(unsigned long)f_ptr)) {
            printf ("Data verification error at 0x%X\n", (unsigned long)f_ptr);
            printf ("Expected 0x%X Got 0x%X\n", (~(unsigned long)f_ptr), *f_ptr);
            goto finish;
        }
        f_ptr++;
        bytes_written += 4;
    }
    printf ("Done Verifying Inverted Longword Data!\n\n");


    printf ("Checking FLASH...\n");
    if (check_eeprom(NO_ADDR, 0) == OK)
        printf("FLASH is erased\n\n");
    else {
        printf("FLASH is programmed between 0x%X and 0x%X\n\n",
	       eeprom_prog_first, eeprom_prog_last);
    }

    printf ("Erasing FLASH...\n");
    if (erase_eeprom(NO_ADDR, 0) != OK)
        printf("Error on erase_eeprom()\n\n");
    else
        printf("Done Erasing FLASH!\n\n");

    printf ("Checking FLASH...\n");
    if (check_eeprom(NO_ADDR, 0) == OK)
        printf("FLASH is erased\n\n");
    else
        printf("FLASH is programmed between 0x%X and 0x%X\n\n",
	       eeprom_prog_first, eeprom_prog_last);

/* 11/02/00 */
    printf ("Setting Lock Bits for Blocks 0-3... \n");
    if( (status = set_all_lock_bits() ) == OK )
        printf("Done!\n");
    else
        printf("Error! status =0x%x\n", status);

finish:
    _flushICache();

    printf ("\nHit <CR> to Continue...\n");
    (void)hexIn();
    return;
}
Ejemplo n.º 20
0
Archivo: ini.c Proyecto: sobomax/digger
void WriteINIString(const char *section,const char *key,const char *value,const char *filename)
{
  FILE *fp;
  char *buffer,*p,*p0,s1[80],s2[80],s3[80];
  int tl;
  fp=fopen(filename,"rb");
  if (fp==NULL) {
    goto do_write;
  }
  fseek(fp,0,2);
  tl=(int)ftell(fp);
  if (tl < 0) {
    goto out_0;
  }
  fseek(fp,0,0);
  buffer=(char *)malloc(tl+1);
  if (buffer==NULL) {
    goto out_0;
  }
  if (fread(buffer, tl, 1, fp) <= 0) {
    fprintf(stderr, "short read, recreating file: %s\n", filename);
    fclose(fp);
    free(buffer);
    goto do_write;
  }
  buffer[tl]=0;
  fclose(fp);
  fp = NULL;
  strcpy(s2,"[");
  strcat(s2,section);
  strcat(s2,"]");
  strcpy(s3,key);
  strcat(s3,"=");
  p=buffer;
  do {
    p=sgets(p,s1);
    if (stricmp(s1,s2)==0) {
      do {
        p0=p;
        p=sgets(p,s1);
        if (strnicmp(s1,s3,strlen(s3))==0) {
          fp=fopen(filename,"wb");
          if (fp==NULL) {
            goto out_1;
          }
          fwrite(buffer,p0-buffer,1,fp);
          fprintf(fp,"%s=%s" NEWL,key,value);
          fwrite(p,tl-(p-buffer),1,fp);
          goto out_1;
        }
      } while (s1[0]!=0);
      fp=fopen(filename,"wb");
      if (fp==NULL) {
        goto out_1;
      }
      fwrite(buffer,p0-buffer,1,fp);
      fprintf(fp,"%s=%s" NEWL,key,value);
      fwrite(p0,tl-(p0-buffer),1,fp);
      goto out_1;
    }
  } while (p<buffer+tl);
  fp=fopen(filename,"wb");
  if (fp==NULL) {
    goto out_1;
  }
  fprintf(fp,"[%s]" NEWL,section);
  fprintf(fp,"%s=%s" NEWL NEWL,key,value);
  fwrite(buffer,tl,1,fp);
out_1:
  free(buffer);
out_0:
  if (fp != NULL) {
    fclose(fp);
  }
  return;
do_write:
  fp = fopen(filename, "wb");
  if (fp == NULL)
    return;
  fprintf(fp, "[%s]" NEWL, section);
  fprintf(fp, "%s=%s" NEWL NEWL, key, value);
  fclose(fp);
  return;
}