示例#1
0
void main(int argc, char **argv)
{
	FILE *fp1;
	char filename[13]="TESTA.TMP";
	int i,num=100;
	register unsigned long j;
	unsigned long mb32=32L*1024L*1024L;
	int n;
	char x;

	if (argc == 2)
	{
		i=toupper(argv[1][0])-'A';
		setdisk(i);
	}

	chdir("\\");
	clrscr();
	while (x!=EOF)
	{
	strcpy(filename,"TEST");
	sprintf(&filename[4],"%3d",num++);
	strcat(filename,".TMP");
	fp1=fopen(filename,"wb");
	printf("\n%c:\\%s  2GB FILE 64 BLOCKS OF 32MB EACH\n[%64s]\r[",getdisk()+ 'A',filename," ");
	for(i=0;i<64;i++)
	{
		for (j=0;j<mb32;j++)
		{
			x=putc(NULL,fp1);
			if (x==EOF)
				j=mb32;
		}
		printf("%c",177);
		if (x==EOF)
			i=64;
	}
	fclose(fp1);
	}
	printf("\n\nDONE\n");
	do
	{
		strcpy(filename,"TEST");
		sprintf(&filename[4],"%3d",--num);
		strcat(filename,".TMP");
		printf("\nDeleting File - %s",filename);
		remove(filename);
	} while (num>100);
	printf("\n\nClearing completed\n");
}
示例#2
0
void GetDrive()
{
    unsigned driveno;

#ifdef __TURBOC__
    driveno = getdisk(); /* get current drive */
    Drive[0] = 'A' + driveno;
#else
    _dos_getdrive(&driveno);
    Drive[0] = (char) driveno + 'A' - 1;
#endif
    valid_drive(Drive);

} /* end GetDrive. */
示例#3
0
文件: lfnapi.c 项目: FDOS/diskcopy
static int
IsLFNSupported (char *filename)
{
  int result;

  if (filename && filename[0] && (filename[1] == ':'))
    result = CheckDriveOnLFN (filename[0]);
  else
    result = CheckDriveOnLFN (getdisk () + 'A');

  if (CriticalErrorOccured ())
    return MAYBE;		/* If this caused a reaction, LFN would be supported.
				   Maybe not on the indicated drive though. */
  else
    return result;
}
示例#4
0
int
DiskLargeEnough (char *imagefile, unsigned long floppysize)
{
  int disk;
  struct dfree free;

  if (imagefile[0] != 0 && imagefile[1] == ':')
    disk = toupper (imagefile[0]) - 65;
  else
    disk = getdisk ();

  getdfree (disk + 1, &free);	/* absread doesn't work on FAT16! */

  return (floppysize <= (long) free.df_avail * (long) free.df_bsec *
	  (long) free.df_sclus);
}
示例#5
0
char  *_RTL_FUNC      getcwd( char  *__buf, int __buflen )
{
    int drv,rv;
    char ibuf[265];
    drv = getdisk() ;
    rv = getcurdir(0,ibuf+3);
    ibuf[0] = drv + 'A';
    ibuf[1] = ':';
    ibuf[2] = '\\';
    if (!__buf)
        __buf = strdup(ibuf) ;
    else {
        memcpy(__buf,ibuf,__buflen);
        __buf[__buflen-1] = 0;
    }
   return __buf;
}
示例#6
0
int main(void)
{
  int maxdrives,curdrive, x;
  unsigned long disksize,diskfree,clustersize,sizesum=0,freesum=0;
  unsigned long capacity;
  char label[41],file_system[256];

  #ifdef __OS2__
   DosError(FERR_DISABLEHARDERR|FERR_ENABLEEXCEPTION);
  #endif

  printf("\nDF/" VERSION_BITS "bit v" VERSION_NO
	 "     Copyright (c) Timo Kokkonen, OH6LXV  "
	 "             " RELEASE_DATE "\n\n");

  curdrive=getdisk();
  maxdrives=setdisk(curdrive);
  if (maxdrives-2<=0) return 1;

  printf("disk               free       used      total capacity  cluster   file system\n");
  for(x=3;x<=maxdrives;x++) {
    label[0]=0;
    file_system[0]=0;
    #ifdef __MSDOS__
    if (!DriveExists(x)) continue;
    #endif
    if (getDiskSize(x,&disksize,&diskfree,&clustersize)) {
      getDiskLabel(x,label);
      strcpy(file_system,getIFSname(x));
    }
    sizesum+=disksize; freesum+=diskfree;
    if (disksize==0) capacity=0;
      else capacity=((disksize-diskfree)/(disksize/100));

    printf("%c:%-12s %8luk  %8luk  %8luk  %3lu%%  %5lu bytes   %-8s \n",
       x+64,label,diskfree/1024,(disksize-diskfree)/1024,disksize/1024,
       capacity,clustersize,file_system);
  }

  printf("\nTotal:        %9luk %9luk %9luk  %3lu%% \n",
     freesum/1024,(sizesum-freesum)/1024,sizesum/1024,
     (sizesum-freesum)/(sizesum/100));

  return 0;
}
示例#7
0
CONSTSTR MYRTLEXP GetCurDir( void )
  {  static char path[ MAX_PATH_SIZE+1 ];

#if defined(__GNUC__) || defined(__QNX__)
    getcwd( path,MAX_PATH_SIZE );
#else
#if defined(__HDOS__) || defined(__HWIN16__)
   strcpy(path, "X:\\");      /* fill string with form of response: X:\ */
   path[0] = 'A' + getdisk();    /* replace X with current drive letter */
   getcurdir(0, path+3);  /* fill rest of string with current directory */
#else
#if defined(__HWIN__)
   GetCurrentDirectory( sizeof(path),path );
#else
#error ERR_PLATFORM
#endif
#endif
#endif
 return AddLastSlash( path );
}
示例#8
0
void TDirListBox::showDrives( TDirCollection *dirs )
{
    Boolean isFirst = True;
    char oldc[5];
    strcpy( oldc, "0:\\" );
    for( char c = 'A'; c <= 'Z'; c++ )
        {
        if( c < 'C' || driveValid( c ) )
            {
            if( oldc[0] != '0' )
                {
                char s[ 16 ];
                if( isFirst )
                    {
                    strcpy( s, firstDir );
                    s[ strlen(firstDir) ] = oldc[0];
                    s[ strlen(firstDir)+1 ] = EOS;
                    isFirst = False;
                    }
                else
                    {
                    strcpy( s, middleDir );
                    s[ strlen(middleDir) ] = oldc[0];
                    s[ strlen(middleDir)+1 ] = EOS;
                    }
                dirs->insert( new TDirEntry( s, oldc ) );
                }
            if( c == getdisk() + 'A' )
                cur = dirs->getCount();
            oldc[0] = c;
            }
        }
    if( oldc[0] != '0' )
        {
        char s[ 16 ];
        strcpy( s, lastDir );
        s[ strlen(lastDir) ] = oldc[0];
        s[ strlen(lastDir)+1 ] = EOS;
        dirs->insert( new TDirEntry( s, oldc ) );
        }
}
示例#9
0
main(void)
{
	unidad_actual = getdisk();
	_setcursortype(_NOCURSOR);
	dibujar_pantalla();
	verificar_disco();
	pedir_unidad();
	verificar_espacio();
	disque_instalar();
	escribir_mensajes();
	dibujar_pantalla();
	ventana(8,11,72,15);
	centrar("El programa de instalaci¢n ha finalizado.", 13);
	delay(3000);
	textcolor(LIGHTGRAY);
	textbackground(BLACK);
	clrscr();
	puts ("DPA Software.");
	_setcursortype(_NORMALCURSOR);
	return 0;
}
示例#10
0
文件: install.cpp 项目: masneyb/misc
void MainScreen(char *InstallName) {
   char fromdrive[2], todrive[3], tmp1[3], topath[9], tmp[9], drive[2];
   EditClass EditToDrive(WINDOW_LEFT+26,WINDOW_TOP+3,1, DEF_DRIVE);
   EditClass EditPath(WINDOW_LEFT+32,WINDOW_TOP+4,8, DEF_DIRECTORY);
   char ok;

   sprintf(fromdrive, "%c", getdisk()+'A');
   strcpy(todrive, "C");
   strcpy(tmp, "\\EDIR");
   _setcursortype(_NORMALCURSOR);
   putxy(WINDOW_LEFT+3,WINDOW_TOP+2,0,STANDARD,"Installing from drive %c:", fromdrive[0]);
   putxy(WINDOW_LEFT+3,WINDOW_TOP+3,0,STANDARD,"Install to what drive?  :");
   putxy(WINDOW_LEFT+3,WINDOW_TOP+4,0,STANDARD,"Install to what directory?  :", topath);
   EditToDrive.Display();
   EditPath.Display();
   putxy(WINDOW_LEFT+30, WINDOW_TOP+4, 0, STANDARD, "%c", toupper(todrive[0]));
   strcpy(todrive, EditToDrive.GetInput());
   putxy(WINDOW_LEFT+30, WINDOW_TOP+4, 0, STANDARD, "%c", toupper(todrive[0]));
   strcpy(tmp, EditPath.GetInput());
   descr(NULL);
   sprintf(topath, "%c:%s", todrive[0], tmp);
   putxy(WINDOW_LEFT+3,WINDOW_TOP+5,0,STANDARD,"Is this ok (Y/N/Q)? ");
   ok = (int) tolower((char) getch());
   if(ok == 121) {
      if(CheckDrive(todrive[0], "Invalid disk drive to copy files to") == 1) {
	 _setcursortype(_NOCURSOR);
	 putxy(WINDOW_LEFT+3,WINDOW_TOP+5,0,STANDARD,"Please wait...installing files...");
	 sprintf(tmp1, "%c:", fromdrive[0]);
	 docopy(tmp1, topath, InstallName);
	 getch();
      }
      else MainScreen(InstallName);
   }
   else if(ok == 113);
   else {
      putxy(WINDOW_LEFT+3,WINDOW_TOP+5,0,STANDARD,"%s", space(20));
      MainScreen(InstallName);
   }
}
示例#11
0
/*-------------------------------------------------------------------------*/
static int xcopy_file(const char *src_filename,
                const char *dest_filename) 
{
  struct stat src_statbuf;
  struct dfree disktable;
  unsigned long free_diskspace;
  unsigned char dest_drive;

  /* Get the destination drive */
  if (dest_filename[1] == ':')
      dest_drive = dest_filename[0];
  else
      dest_drive = getdisk() + 'A' - 1;
  
  
  /* get info of source and destination file */
  stat((char *)src_filename, &src_statbuf);

  /* get amount of free disk space in destination drive */
  getdfree(dest_drive-'A'+1, &disktable);
  free_diskspace = (unsigned long) disktable.df_avail *
                   disktable.df_sclus * disktable.df_bsec;

  /* check free space on destination disk */
  if (src_statbuf.st_size > free_diskspace) 
  {
#ifdef USE_KITTEN
      error(1,29,"Insufficient disk space in destination path");
#else
      error("Insufficient disk space in destination path");
#endif
      return(0);
  }

  /* Copy file data */
  return copy_file(src_filename, dest_filename);
}
示例#12
0
//============================================================fim_interrupcoes
void
loadcfg()
{
	FILE *fp;
	if (!(fp = fopen(cfg_file, "rb"))) {
		config.ativo.full = 0;
		config.ativo.half.letra = BLACK;
		config.ativo.half.fundo = GREEN;
		config.inativo.full = 0;
		config.inativo.half.letra = GREEN;
		config.inativo.half.fundo = BLACK;
		config.menu_ativo.full = 0;
		config.menu_ativo.half.letra = LIGHTGRAY;
		config.menu_ativo.half.fundo = BLACK;
		config.menu_inativo.full = 0;
		config.menu_inativo.half.letra = BLACK;
		config.menu_inativo.half.fundo = LIGHTGRAY;
		config.drive = getdisk();
	}

	else
		fread(&config, sizeof(CONFIG), 1, fp);
	fclose(fp);
}
示例#13
0
文件: dir.c 项目: TijmenW/FreeDOS
int cmd_vol(char *rest)
{
  int drive;

  assert(rest);

  /* save the current directory info */
      line = 0;
      optB = 0;

  if (rest && *rest)
  {
    if ((strlen(rest) != 2) || (rest[1] != ':'))
    {
      displayString(TEXT_ERROR_INVALID_PARAMETER, rest);
      return E_Useage;
    }
  drive = toupper(rest[0]) - 'A';
  }
  else
    drive = getdisk();

  return dir_print_header(drive);
}
示例#14
0
文件: path.c 项目: doniexun/OrangeC
char *_RTL_FUNC _fullpath(char *absPath, const char *relPath, size_t len)
{
	char result[MAXPATH], *p;
	int disk = getdisk();
	result[0] = disk + 'A';
	result[1] = ':';
	result[2] = '\\';
	if (getcurdir(disk+1, result + 3) < 0)
	{
		errno = ENOENT;
		return NULL;
	}
	if (relPath && *relPath)
	{
		if (relPath[1] == ':')
		{
			disk = toupper(relPath[0]) - 'A';
			result[0] = disk + 'A';
			relPath += 2;
			if (getcurdir(disk+1, result + 3) < 0)
			{
				errno = ENOENT;
				return NULL;
			}
		}
		if (*relPath == '\\' || *relPath == '/')
		{
			relPath++;
			p = result+2;
		}
		else
		{
			p = result + strlen(result) - 1;
			if (*p != '\\')
				*++p = '\\';
		}
		while (*relPath)
		{
			if (relPath[0] == '.' && (relPath[1] == '\\' || relPath[1] == '/'))
				relPath+=2;
			else if (relPath[0] == '.' && relPath[1] == '.' && 
					(relPath[2] == '\\' || relPath[2] == '/'))
			{
				relPath += 3;
				p--; /* won't get here if p isn't pointing to a '\\' */
				while (*p != '\\' && *p != ':')
					p--;
				if (*p == ':')
					return NULL;
			}
			else
			{
				while (*relPath && *relPath != '\\' && *relPath != '/')
					*++p = *relPath++;
				if (*relPath)
				{
					*++p = '\\';
					relPath++;
				}
			}
		}
		*++p = 0;
	}
	if (!absPath)
	{
		if (!(absPath = strdup(result)))
		{
			errno = ENOMEM;
			return NULL;
		}
	}
	else if (strlen(result) > len-1)
	{
		errno = ERANGE;
		return NULL;
	}
	else strcpy(absPath, result);
	return absPath;
}
示例#15
0
文件: prprompt.c 项目: FDOS/freecom
void displayPrompt(const char *pr)
{
#ifdef FEATURE_ENVVARS_IN_PROMPT
	char *buf = strdup(pr);
	char *expanded = malloc(MAX_INTERNAL_COMMAND_SIZE + sizeof(errorlevel) * 8);

	if(buf && expanded) {
		if(!expandEnvVars(buf, expanded))
			error_line_too_long();
		else
			pr = expanded;
	}
	free(buf);
#endif

  while (*pr)
  {
    if(*pr != '$') {
      outc(*pr);
    } else {
      switch (toupper(*++pr)) {
      case 'A': outc('&'); break;
      case 'B': outc('|'); break;
      case 'C': outc('('); break;
      /* case 'D': see below */
      case 'E': outc(27);  break; /* Decimal 27 */
      case 'F': outc(')');  break;
      case 'G': outc('>'); break;
      case 'H': outc(8);   break; /* Decimal 8 */
      case 'L': outc('<'); break;
      /* case 'M': outc('<'); break; remote name of current drive */
      /* case 'N': see below */
      /* case 'P': see below */
      case 'Q': outc('='); break;
      case 'S': outc(' '); break;
      /* case 'T': see below */
      /* case 'V': see below */

      case '$': outc('$'); break;
      case '_': outc('\n'); break;
      /* case '+': see below */

        case 'D':
          {	 char *p;
          	 if((p = curDateLong()) != 0) {
          	 	outs(p);
          	 	free(p);
          	 }
            break;
          }
        case 'N':
          {
            outc( ( getdisk() + 'A' ) );
            break;
          }
        case 'P':
          {
#ifdef FEATURE_LONG_FILENAMES
            char pathname[MAXDIR];
            IREGS r;
            printf("%c:\\", getdisk() + 'A');

            r.r_ax = 0x7147;
            r.r_dx = 0;
            r.r_si = FP_OFF(pathname);
            r.r_ds = FP_SEG(pathname);

            intrpt(0x21, &r);

            if(r.r_flags & 1 || r.r_ax == 0x7100) {
                r.r_ax = 0x4700;
                intrpt(0x21, &r);
            }

            if(r.r_flags & 1) break;

            outs(pathname);
#else
            char *p;

            if((p = cwd(0)) != 0) {
                outs(p);
                free(p);
            }
#endif

            break;
          }
        case 'T':
          {
            char *p;

            if((p = curTime()) != 0) {
				outs(p);
				free(p);
			}

            break;
          }
        case 'V':
          {
            /* #1776 fputs(shellname, stdout); */
            printf("%s v%s", shellname, shellver);
            break;
          }
        case '+':	/* Levels of PUSHD */
         {
#ifdef INCLUDE_CMD_PUSHD
			ctxt_info_t *info;
			int i;

			info = &CTXT_INFO_STRUCT(CTXT_TAG_DIRSTACK);
			assert(info);
			if((i = info->c_nummax) > 0) do {
				outc('+');
			} while(--i);
#endif
         }
      }
    }
    pr++;
  }
#ifdef FEATURE_ENVVARS_IN_PROMPT
	free(expanded);
#endif
}
示例#16
0
文件: FCTOOLS.C 项目: FDOS/fc
/* ************************************************************************ */
char* FullPath(char* Buffer, char *Path, int BufferSize)
{
  struct REGPACK r;
  char Drive;
  int Work;
  char* WorkPointer = Buffer;

  *Buffer = END_OF_STRING;
  if (BufferSize < MAXPATHLFN) return Buffer;

  if (isalpha(Path[0]) && (Path[1] == ':'))    /* Drive specified */
  {
    Drive = WorkPointer[0] = Path[0];
    Path += 2;
  }
  else					 /* Default drive */
    Drive = WorkPointer[0] = getdisk() + 'A';
  WorkPointer[1] = ':';
  WorkPointer += 2; BufferSize -= 2;

  if (islower(Drive)) Drive = _toupper (Drive); /* Upper case drive */
  Drive = Drive - 'A' + 1;

  *WorkPointer = '\\';
  WorkPointer++; BufferSize -= 1;
  if (*Path == '\\')
    Path++;			/* Absolute path */
  else
  {				/* Relative path */
    r.r_ax = 0x7147;		/* Get current directory (LFN) */
    r.r_dx = Drive;
    r.r_ds = FP_SEG(WorkPointer);  r.r_si = FP_OFF(WorkPointer);
    r.r_flags = CARRY;	/* Set carry to prepare for failure */
    intr(DOS, &r);
    if ((r.r_flags & CARRY) != 0)	/* Carry -> Not ok */
      getcurdir(Drive, WorkPointer);	/* Use the SFN function */

    if (*WorkPointer != END_OF_STRING)
    {
      Work = strlen(WorkPointer);
      WorkPointer += Work;
      *WorkPointer = '\\';
      WorkPointer++;
      BufferSize -= Work + 1;
    }
  }

  strncpy(WorkPointer, Path, BufferSize);  /* Add the rest of the path */

  WorkPointer = Buffer;		/* Expand the "." directories */
  do
  {
    WorkPointer = strchr(WorkPointer, '.');
    if (WorkPointer == NULL) break;

    switch (WorkPointer[1])
    {
      case '\\':                        /* ".\" */
	stpcpy(WorkPointer, WorkPointer + 2);
	break;

      case END_OF_STRING:		/* Terminal '.' */
	if (WorkPointer[-1] == '\\')    /* "\." */
	  *WorkPointer = END_OF_STRING;
	else
	  WorkPointer++;		/* "FOO." */
	break;

      case '.':
	if (WorkPointer[-1] == '\\')    /* "\.." */
	{
	  Path = WorkPointer + 1;
	  do { Path++; } while (*Path == '.');

	  if ((*Path != '\\') && (*Path != END_OF_STRING))
	    WorkPointer = Path;
	  else
	  {
	    Work = (int)(Path - WorkPointer - 1);
	    do
	    {
	      WorkPointer--;
	      do
	      {
		WorkPointer--;
		/* Handle the case (absurd) C:\.. */
		if (*WorkPointer == ':')
		{
		  *Buffer = END_OF_STRING;
		  return Buffer;
		}
	      } while (*WorkPointer != '\\');
	      Work--;
	    } while (Work > 0);
	    stpcpy(WorkPointer, Path);
	  }
	}
	break;

      default:
	WorkPointer++;
    }
  } while (TRUE);

  /* Remove the last '\' if not the root directory */
  Work = strlen(Buffer) - 1;
  if ((Work > 3) && (Buffer[Work] == '\\')) Buffer[Work] = END_OF_STRING;

  return Buffer;
}
示例#17
0
char *fullpath95(char * const Xbuffer, const char *path, int Xbuflen)
{
	int drive, buflen;
	char *p;	/* points to place, where to start a new path component */
	char *buffer;	/* buffer to be work over */
	char *lowbound;	/* boundary never to undergo */
	const char *pp;

	assert(path);

	if((buflen = Xbuflen) <= 0)
		buflen = MAXPATH95;
	if((buffer = Xbuffer) == NULL && (buffer = malloc(buflen)) == NULL)
		return NULL;

	if(*path == '\\' && path[1] == '\\') {	/* assume an UNC path */
		/* two shares must be present! */
		if(*(pp = &path[2]) == '\\' || *pp == '/')
			goto errRet;
		while(*pp && *pp != '\\' && *pp != '/') ++pp;
		if(!*pp) goto errRet;			/* at least two shares */
		while(*pp && *pp != '\\' && *pp != '/') ++pp;
		if(buflen <= (drive = pp - path))
			goto errRet;
		memcpy(buffer, path, drive);
		path = pp;
		lowbound = p = buffer + drive;
	}
	else {
		lowbound = buffer + 2;
		if(path[1] == ':') {
			if(!isalpha(*path))
				goto errRet;		/* invalid file spec */
			drive = toupper(path[0]) - 'A';
			path += 2;
		}
		else
			drive = getdisk();		/* current drive */

		if(*path == '\\' || *path == '/') {
			/* fully-qualified path needn't getcwd */
			*buffer = drive + 'A';
			buffer[1] = ':';
			*(p = &buffer[2]) = '\0';
		}
		else if(!getdcwd95(drive + 1, buffer, buflen))	/* get working directory failed */
			goto errRet;
		else if((p = strchr(buffer, '\0'))[-1] == '\\')
			--p;
	}

   /*
	Now copy all remaining components from path to buffer
   */

	do {
		/* first chop path delimiter characters */
		while(*path == '/' || *path == '\\') ++path;
		/* second break, if path has been used up */
		if(!*path) break;
		/* third identify '.' and '..' */
		if(*path == '.') switch(path[1]) {
			case '/': case '\\': case '\0':
				++path;		/* skip '.' */
				continue;
			case '.':		/* probably: '..' */
				switch(path[2]) {
				case '/': case '\\': case '\0':
					path += 2;		/* skip '..' */
					/* chop last path component */
					while(--p > lowbound && *p != '/' && *p != '\\');
					continue;
				}
				break;
		}
		/* forth copy this path component */
		*p++ = '\\';
		while(*path && *path != '/' && *path != '\\')
			if(p >= buffer + buflen)
				goto errRet;		/* buffer overflow */
			else *p++ = *path++;
	} while(1);

	if(p == lowbound)		/* root drive */
		*p++ = '\\';
	*p = '\0';

	if(!Xbuffer && Xbuflen <= 0
	 && (p = realloc(buffer, strlen(buffer) + 1)) != NULL)
	 	return p;

	return buffer;

errRet:
	if(!Xbuffer)
		free(buffer);

	return NULL;
}
示例#18
0
void
kpse_set_program_name P2C(const_string, argv0, const_string, progname)
{
  string ext, sdir, sdir_parent, sdir_grandparent;
  string s = getenv ("KPATHSEA_DEBUG");
#ifdef WIN32
  string debug_output = getenv("KPATHSEA_DEBUG_OUTPUT");
  string append_debug_output = getenv("KPATHSEA_DEBUG_APPEND");
  int err, olderr;
#endif
  
  /* Set debugging stuff first, in case we end up doing debuggable stuff
     during this initialization.  */
  if (s) {
    kpathsea_debug |= atoi (s);
  }

#ifndef HAVE_PROGRAM_INVOCATION_NAME
#if defined(WIN32)
  /* Set various info about user. Among many things,
     ensure that HOME is set. If debug_paths is on, 
     turn on some message if $HOME is not found. */
  if (KPSE_DEBUG_P(KPSE_DEBUG_PATHS)) {
    set_home_warning();
  }
  init_user_info();

  /* redirect stderr to debug_output. Easier to send logfiles. */
  if (debug_output) {
    int flags =  _O_CREAT | _O_TRUNC | _O_RDWR;
    err = -1;
    if (_stricmp(debug_output, "con") == 0
       || _stricmp(debug_output, "con:") == 0) {
      err = _fileno(stdout);
    } else {
      if (append_debug_output) {
        flags =  _O_CREAT | _O_APPEND | _O_WRONLY;
      } else {
        flags =  _O_CREAT | _O_TRUNC | _O_WRONLY;
        xputenv("KPATHSEA_DEBUG_APPEND", "yes");
      }
    }

    if ((err < 0)
        && (err = _open(debug_output, flags, _S_IREAD | _S_IWRITE)) == -1)
    {
      WARNING1("Can't open %s for stderr redirection!\n", debug_output);
      perror(debug_output);
    } else if ((olderr = _dup(fileno(stderr))) == -1) {
      WARNING("Can't dup() stderr!\n");
      close(err);
    } else if (_dup2(err, fileno(stderr)) == -1) {
      WARNING1("Can't redirect stderr to %s!\n", debug_output);
      close(olderr);
      close(err);
    } else {
      close(err);
    }
  }
  /* Win95 always gives the short filename for argv0, not the long one.
     There is only this way to catch it. It makes all the selfdir stuff
     useless for win32. */
  {
    char short_path[PATH_MAX], path[PATH_MAX], *fp;
      
    /* SearchPath() always gives back an absolute directory */
    if (SearchPath(NULL, argv0, ".exe", PATH_MAX, short_path, &fp) == 0)
        FATAL1("Can't determine where the executable %s is.\n", argv0);
    if (!win32_get_long_filename(short_path, path, sizeof(path))) {
        FATAL1("This path points to an invalid file : %s\n", short_path);
    }
    /* slashify the dirname */
    for (fp = path; fp && *fp; fp++)
        if (IS_DIR_SEP(*fp)) *fp = DIR_SEP;
    /* sdir will be the directory of the executable, ie: c:/TeX/bin */
    sdir = xdirname(path);
    program_invocation_name = xstrdup(xbasename(path));
  }

#elif defined(__DJGPP__)

  /* DJGPP programs support long filenames on Windows 95, but ARGV0 there
     is always made with the short 8+3 aliases of all the pathname elements.
     If long names are supported, we need to convert that to a long name.

     All we really need is to call `_truename', but most of the code
     below is required to deal with the special case of networked drives.  */
  if (pathconf (argv0, _PC_NAME_MAX) > 12) {
    char long_progname[PATH_MAX];

    if (_truename (argv0, long_progname)) {
      char *fp;

      if (long_progname[1] != ':') {
	/* A complication: `_truename' returns network-specific string at
	   the beginning of `long_progname' when the program resides on a
	   networked drive, and DOS calls cannot grok such pathnames.  We
	   need to convert the filesystem name back to a drive letter.  */
	char rootname[PATH_MAX], rootdir[4];

	if (argv0[0] && argv0[1] == ':')
	  rootdir[0] = argv0[0]; /* explicit drive in `argv0' */
	else
	  rootdir[0] = getdisk () + 'A';
	rootdir[1] = ':';
	rootdir[2] = '\\';
	rootdir[3] = '\0';
	if (_truename (rootdir, rootname)) {
	  /* Find out where `rootname' ends in `long_progname' and replace
	     it with the drive letter.  */
	  int root_len = strlen (rootname);

 	  if (IS_DIR_SEP (rootname[root_len - 1]))
            root_len--;	/* keep the trailing slash */
	  long_progname[0] = rootdir[0];
	  long_progname[1] = ':';
	  memmove (long_progname + 2, long_progname + root_len,
		   strlen (long_progname + root_len) + 1);
	}
      }

      /* Convert everything to canonical form.  */
      if (long_progname[0] >= 'A' && long_progname[0] <= 'Z')
	long_progname[0] += 'a' - 'A'; /* make drive lower case, for beauty */
      for (fp = long_progname; *fp; fp++)
	if (IS_DIR_SEP (*fp))
	  *fp = DIR_SEP;

      program_invocation_name = xstrdup (long_progname);
    }
    else
      /* If `_truename' failed, God help them, because we won't...  */
      program_invocation_name = xstrdup (argv0);
  }
  else
    program_invocation_name = xstrdup (argv0);

#else /* !WIN32 && !__DJGPP__ */

  program_invocation_name = xstrdup (argv0);

#endif
#endif /* not HAVE_PROGRAM_INVOCATION_NAME */

  /* We need to find SELFAUTOLOC *before* removing the ".exe" suffix from
     the program_name, otherwise the PATH search inside selfdir will fail,
     since `prog' doesn't exists as a file, there's `prog.exe' instead.  */
#ifndef WIN32
  sdir = selfdir (program_invocation_name);
#endif
  /* SELFAUTODIR is actually the parent of the invocation directory,
     and SELFAUTOPARENT the grandparent.  This is how teTeX did it.  */
  xputenv ("SELFAUTOLOC", sdir);
  sdir_parent = xdirname (sdir);
  xputenv ("SELFAUTODIR", sdir_parent);
  sdir_grandparent = xdirname (sdir_parent);
  xputenv ("SELFAUTOPARENT", sdir_grandparent);

  free (sdir);
  free (sdir_parent);
  free (sdir_grandparent);

#ifndef HAVE_PROGRAM_INVOCATION_NAME
  program_invocation_short_name = (string)xbasename (program_invocation_name);
#endif

  if (progname) {
    kpse_program_name = xstrdup (progname);
  } else {
    /* If configured --enable-shared and running from the build directory
       with the wrapper scripts (e.g., for make check), the binaries will
       be named foo.exe instead of foo.  Or possibly if we're running on a
       DOSISH system.  */
    ext = find_suffix (program_invocation_short_name);
    if (ext && FILESTRCASEEQ (ext, "exe")) {
      kpse_program_name = remove_suffix (program_invocation_short_name);
    } else {
      kpse_program_name = xstrdup (program_invocation_short_name);
    }
  }
  xputenv("progname", kpse_program_name);
}
示例#19
0
文件: dfnexpan.c 项目: FDOS/freecom
char *dfnexpand(const char * const fnam, char * const path)
{	char *h, *p;				/* intermediate pointers */
	char *dr, *pa, *na, *ex;	/* filename components */
	char pathDr, *pathPa;		/* drive & path of 'path' */
	char *dynPath;

#ifdef SUPPORT_UNC_PATH
	DBG_ENTER("dfnuexpand", Suppl_dfn)
#else
	DBG_ENTER("dfnexpand", Suppl_dfn)
#endif

	assert(fnam);

	DBG_ARGUMENTS( ("fnam=\"%s\", path=\"%s\"", fnam, path) )

	chkHeap
	if((h = dfnsqueeze(fnam)) == 0) 
		DBG_RETURN_S( 0)

#ifdef SUPPORT_UNC_PATH
	if(isUNCpath(h)) {			/* UNC paths are always fully-qualified */
		/* check if the trailing '\\' is present to mark the root direc */
		DBG_RETURN_BS((*UNCpath(h) != '\\')? StrAppChr(h, '\\') : h)
	}
#endif

	chkHeap
	if(!*h || h[1] != ':' || h[2] != '\\') {
	/* the spec is not fully-qualified or completely empty */
		pathDr = 0;
		dynPath = 0;
		if((pathPa = path) != 0 && *pathPa) {
			if(pathPa[1] == ':') {	/* path[] has drive spec */
				pathDr = *path;
				if(!*(pathPa += 2)) {
					pathPa = 0;
					goto noPath;
				}
			}
			if(dfndelim(*pathPa) && !pathPa[1])
				++pathPa;		/* Trans "/" || "\\" --> "" */
noPath:;
		}
		chkHeap
		if(dfnsplit(h, &dr, &pa, &na, &ex)) {
			StrFree(h);
			if(dr) {				/* drive specified */
				if(pathDr && toFUpper(pathDr) != *dr)
					/* The specified path is for a different drive */
					pathPa = 0;
			}
			else {					/* drive spec missing */
				if((dr = StrChar(pathDr? pathDr: 'A' + getdisk())) == 0)
					goto errRet;
			}

			if(!pa || *pa != '\\' && *pa != NUL) {
			/* no path or a relative one */
				if(!pathPa) {				/* path has no path spec in it */
					if((dynPath = dfnpath(*dr)) == 0)
						goto errRet;
					pathPa = dynPath + 2;
				}

				if((p = dfnmerge(0, 0, pathPa, pa, 0)) == 0)
					goto errRet;
 				StrRepl(pa, p);
			}
			h = dfnmerge(0, dr, pa, na, ex);
		} else
			StrFree(h);

errRet:
		chkHeap
		free(dr);
		free(pa);
		free(na);
		free(ex);
		free(dynPath);
	}
示例#20
0
static unsigned long DriverList(HWND Window,HMSG Message,long Param1,long Param2)
{
  switch (Message)
  {
    case WINDOWINIT:
         {
           unsigned save,disk,total,UnusedDisk;
           char diskn[3];
           char *dri=diskn;

           diskn[1] = ':';
           diskn[2] = '\0';

           MessageGo(Window,LISTSETITEMHEIGHT,16,0);
           MessageGo(Window,LISTSETITEMLENGTH,3,0);

               /* save original drive */
           save = getdisk();
//           diskn[0] = save+'A';
           diskn[0] = save+'A'-1;
//           _harderr(handler);
           MessageGo(Window,SETLINEBUFFER,FP2LONG(dri),0L);
           MessageGo(Window,LISTDELETEALL,0L,0L);

       /*------------
           for (disk = 1;disk < 26;++disk) {
                 setdisk(disk);
                 if (disk == getdisk()) {
                      setdisk(save);
       ------------*/

           disk = 1;            // from diskette A:
           UnusedDisk=0;
           {                         // ByHance, for diskette error
                 char *p=(char *)0x410;           // equipment list
                 total=*p;
                 if(total&1) {          // diskette present, count how many
                    total=(total>>6)&0x3;
                    if(!total) UnusedDisk=2;    // if only 1, can not use B:
                 } else disk=3;         // no diskette present, so, from C:
           }
           for (; disk<26; ++disk) {
                 if(disk==UnusedDisk) continue;
                 _dos_setdrive(disk,&total);
                 if (disk == getdisk()) {
                      _dos_setdrive(save,&total);
                      if(first && disk==save) {           // ByHance
                          HWND MidWindow=ComboFindListBox(Window);
                          if (MidWindow)
                               ListSetCurrent(WindowList(MidWindow),
                                        ListGetTotal(WindowList(MidWindow)) );
                          first=0;
                      }
                      diskn[0] = disk+'A'-1;
                      MessageGo(Window,LISTAPPENDITEM,FP2LONG(dri),0L);
                 }
           }

       /*---------
           setdisk(save);
           diskn[0] = save+'A';
        ----------*/
           _dos_setdrive(save,&total);
           diskn[0] = save+'A'-1;

           strcpy(NowOpenFile->drive,diskn);
         }
示例#21
0
static unsigned long DirectoryList(HWND Window,HMSG Message,long Param1,long Param2)
{
  int hlist;

  switch (Message)
  {
    case WINDOWINIT:
         {
           //int   i,j;
           char  *dirs=NowOpenFile->dirs;
           char  *drive=NowOpenFile->drive;
           #ifdef _TURBOC_
              struct ffblk opffblk;
           #else
              struct find_t opffblk;
           #endif

           char  fn[128];
           int   r;

           MessageGo(Window,LISTSETITEMHEIGHT,16,0);
           MessageGo(Window,LISTSETITEMLENGTH,13,0);

           /*------ ByHance, 96,3.25 ----
           hlist = WindowList(Window);
           ListSetTotal(hlist,0);
           ListSetCurrent(hlist,0);
           ListSetTop(hlist,0);
           --------------------*/
           MessageGo(Window,LISTDELETEALL,0L,0L);

//           _harderr(handler);
           if( ! drive[0] )
            {
 //             *drive     = (char)getdisk()+'A';
             *drive     = (char)getdisk()+'A'-1;
             *(drive+1) = ':';
             *(drive+2) = 0;
            }

           if( !dirs[0] ) {
              #ifdef __TURBOC__
                 getcurdir((int)(*drive-'A'+1), dirs);
              #else
                 unsigned total,old;
                 _dos_getdrive(&old);
                 if(old!=*drive-'A'+1)
                    _dos_setdrive( *drive-'A'+1 , &total );
                 getcwd(dirs, 64);
                 memmove(dirs,dirs+3,61);       // cancel "C:\"
                 if(!dirs[0])
                     strcpy(dirs,"\\");
                 if(old!=*drive-'A'+1)
                    _dos_setdrive( old, &total );
              #endif
           }

           memset(&opffblk, 0, sizeof(opffblk));
           strcpy(fn,drive);

           //if( strcmp(dirs,"\\") && strcmp(dirs,"/") )
           //{
           //    strcat(fn,dirs);
           //    strcat(fn,"\\");
           //}
           if(dirs[0])
           {
                  char ch;
                  int len;

                  ch=dirs[0];
                  if(ch!='\\' && ch!='/')
                       strcat(fn,"\\");

                  strcat(fn,dirs);
                  len=strlen(fn);
                  ch=fn[len-1];
                  if(ch!='\\' && ch!='/')
                       strcat(fn,"\\");
           }

           strcat(fn,"*.*");

           r = findfirst(fn, &opffblk, FA_DIREC);
           while (!r)
           {
            if((opffblk.ff_attrib & FA_DIREC) && strcmp(opffblk.ff_name,"."))
              MessageGo(Window, LISTINSERTITEMSORTED, FP2LONG(opffblk.ff_name), 0L);
            r = findnext(&opffblk);
           }

           //MessageGo(Window,WMPAINT,0,ListGetHeight(hlist)*CHARHEIGHT);
           //   ByHance, 95,12.11
           MessageInsert(Window,REDRAWMESSAGE,0L,
               MAKELONG(WindowGetWidth(Window),WindowGetHeight(Window)) );

           {    /*--- display directory's name ----*/
              #define max_n  (304/ASC16WIDTH)
                 int x,y,w,h;
                 unsigned total,old;
                 int len;
                 int SaveColor;
                 struct viewporttype TmpViewPort;
                 char disk[20],dirs[64],file[14],ext[5];

                 strupr(fn);
                 _splitpath(fn,disk,dirs,file,ext);

                 _dos_getdrive(&old);
                 if(old!=disk[0]-'A'+1)
                    _dos_setdrive( disk[0]-'A'+1 , &total );
                 len=strlen(dirs);
                 if(len>1)
                 {
                   char ch=dirs[len-1];
                   if(ch=='\\' || ch=='/') dirs[len-1]=0;
                 }

                 chdir(dirs);
                 getcwd(dirs, 64);
                 _dos_setdrive( old, &total );

                 MouseHidden();
                 SaveColor=getcolor();
                 getviewsettings(&TmpViewPort);
                 setviewport(0,0,getmaxx(),getmaxy(),1);

                 WindowGetRealRect(Window,&x,&y,&w,&h);
                 y-=26;

                 len=strlen(dirs);
                 if(len>max_n)
                 {
                    int i;
                    i=len-1;
                    while(dirs[i]!='\\' && dirs[i]!='/' && i>max_n-12) i--;
                    strcpy(dirs,"...");
                    strcat(dirs,&dirs[i]);
                 }

                 // WaitMessageEmpty();
                 setfillstyle(1,EGA_LIGHTGRAY);
                 bar(x,y,x+304,y+25);            /*--- clear old area --*/
                 DisplayString(dirs,x,y,EGA_BLACK,EGA_LIGHTGRAY);

                 setviewport(TmpViewPort.left,TmpViewPort.top,TmpViewPort.right,
                             TmpViewPort.bottom,TmpViewPort.clip);
                 setcolor(SaveColor);
                 MouseShow();
              #undef max_n
            }
         }
         break;

    case LISTBOXCONFIRM:{
         char dir[20];
         char path[40];

         hlist = WindowList(Window);
         strcpy(dir,ListGetItem(hlist,ListGetCurrent(hlist)));
         strcpy(path,NowOpenFile->drive);
         strcat(path,dir);
         chdir(path);
         #ifdef __TURBOC__
            getcurdir(path[0]-'A'+1,NowOpenFile->dirs);
         #else
         {
            unsigned total,old;
            _dos_getdrive(&old);
            if(old!=path[0]-'A'+1)
               _dos_setdrive( path[0]-'A'+1 , &total );
            getcwd(NowOpenFile->dirs, 64);
            memmove(NowOpenFile->dirs,NowOpenFile->dirs+3,61); // cancel "C:\"
            if(old!=path[0]-'A'+1)
               _dos_setdrive( old, &total );
         }
         #endif

         MessageGo(Window,WINDOWINIT,0,0);
         MessageGo(Window,WMPAINT,0,ListGetHeight(hlist)*CHARHEIGHT);
         ListSetTop(hlist,0);
         ListSetCurrent(hlist,0);
         MessageGo(WindowGetFather(Window),DIRCHANGE,0L,0L);
         }
         break;
    default:
         return(ListBoxDefaultProcedure(Window,Message,Param1,Param2));
  }
  return(TRUE);
}
示例#22
0
文件: find.c 项目: CivilPol/sdcboot
int
main (int argc, char **argv)
{
  char *s, *needle;
  int c, i, done, ret;

  unsigned drive /* , thisdrive */ ;       /* used to store, change drive */
  char cwd[MAXPATH], thiscwd[MAXPATH95];    /* used to store, change cwd */
  char cwd2[MAXPATH];             /* store cwd of other drive */

  /* char drv[MAXDRIVE]; */      /* temporary buffer */
  unsigned drv;            /* drive found in argument */
  /* unsigned maxdrives; */      /* not used */

  int invert_search = 0;      /* flag to invert the search */
  int count_lines = 0;        /* flag to whether/not count lines */
  int number_output = 0;      /* flag to print line numbers */
  int ignore_case = 0;        /* flag to be case insensitive */

  /* FILE *pfile; */       /* file pointer */
  int thefile;          /* file handler */
  nl_catd cat;          /* message catalog */
  /* struct ffblk ffblk; */      /* findfirst, findnext block */
  char file[MAXPATH], longfile[MAXPATH95]; 

  /* Message catalog */

  cat = catopen ("find", 0);

  /* Scan the command line */
  c = 1; /* argv[0] is the path of the exectutable! */


  /* first, expect all slashed arguments */
  while ((c < argc) && (argv[c][0] == '/') ) {
      /* printf("arg: %s\n",argv[c]); */
      switch (argv[c][1]) {
     case 'c':
     case 'C':    /* Count */
       count_lines = 1;
       break;

     case 'i':
     case 'I':    /* Ignore */
       ignore_case = 1;
       break;

     case 'n':
     case 'N':    /* Number */
       number_output = 1;
       break;

     case 'v':
     case 'V':    /* Not with */
       invert_search = 1;
       break;

     default:
       usage (cat);
       catclose (cat);
       exit (2);     /* syntax error .. return errorlevel 2 */
       break;
       
      } /* end case */
      c++;  /* next argument */
  } /* end while */

  /* Get the string */

  if (c >= argc)
    {
      /* No string? */
      /* printf("no string"); */
      usage (cat);
      catclose (cat);
      exit (1);
    }
  else
    {
      /* Assign the string to find */
      needle = argv[c];
      c++; /* next argument(s), if any: file name(s) */
      /* printf("needle: %s\n",needle); */
    }



  /* Store the drive and cwd */

  /* findfirst/findnext do not return drive and cwd information, so we
     have to store the drive & cwd at the beginning, then chdir for
     each file we scan using findfirst, then chdir back to the initial
     drive & cwd at the end.  This is probably not the most efficient
     way of doing it, but it works.  -jh */

  /* _dos_getdrive (&drive); */     /* 1 for A, 2 for B, ... */
  drive = getdisk() + 1; /* uses dir.h */
  getcwd (cwd, MAXDIR);       /* also stores drive letter */

#if 0 /* debugging */
  /* printf ("drive=%c\n", (drive+'A'-1)); */
  /* printf ("cwd=%s\n", cwd); */
#endif /* debugging */

  /* Scan the files for the string */

  if ((argc - c) <= 0)
    {
      /* No files on command line - scan stdin */
      ret = find_str (needle, 0 /* stdin */,
        invert_search, count_lines, number_output, ignore_case);
    }

  else
    {
      for (i = c; i < argc; i++)
   {
     /* find drive and wd for each file when using findfirst */

     /* fnsplit (argv[i], drv, thiscwd, NULL, NULL); */
     /* fnsplit is "expensive", so replace it... */
     
     if (argv[i][1] == ':') {
       drv = toupper(argv[i][0]) - 'A';
       strcpy(thiscwd,argv[i]+2);
     } else {
       drv = drive - 1; /* default drive */
       strcpy(thiscwd,argv[i]);
     }

     if (strrchr(thiscwd,'\\') == NULL) {
       strcpy(thiscwd,"."); /* no dir given */
     } else {
       if (strrchr(thiscwd,'\\') != thiscwd) {
         strrchr(thiscwd,'\\')[0] = '\0'; /* end string at last \\ */
       } else {
         strcpy(thiscwd,"\\"); /* dir is root dir */
       }
     }

     if (!LFNConvertToSFN(thiscwd))
     {
       s = catgets (cat, 2, 2, "Cannot change to directory");
       /* printf ("FIND: %s: %s\n", argv[i], s); */
       write(1,"FIND: ",6);
       write(1,argv[i],strlen(argv[i]));
       write(1,": ",2);
       write(1,s,strlen(s));
       write(1,"\r\n",2);          
     }

     /* printf("drive (0=A:)=%d dir=%s\n", drv, thiscwd); */

     /* use findfirst/findnext to expand the filemask */

     /* done = findfirst (argv[i], &ffblk, 0); */
     done = LFNFirstFile(argv[i], file, longfile);

     if (done)
       {
         /* We were not able to find a file. Display a message and
       set the exit status. */

         s = catgets (cat, 2, 1, "No such file");
         /* printf ("FIND: %s: %s\n", argv[i], s); */
         write(1,"FIND: ",6);
         write(1,argv[i],strlen(argv[i]));
              write(1,": ",2);
         write(1,s,strlen(s));
         write(1,"\r\n",2);
       }

     while (!done)
       {
         /* We have found a file, so try to open it */

         /* set cwd to the filemask */

         /* _dos_setdrive (('A' - drv[0] + 1), &maxdrives); */
         /* this was the wrong way round! */

         (void) setdisk (drv /* drv[0] - 'A' */); /* dir.h */
         
         getcwd(cwd2,MAXDIR); /* remember cwd here, too */

         if (chdir (thiscwd) < 0) {
        s = catgets (cat, 2, 2, "Cannot change to directory");
        /* printf ("FIND: %s: %s\n", argv[i], s); */
             write(1,"FIND: ",6);
             write(1,argv[i],strlen(argv[i]));
             write(1,": ",2);
             write(1,s,strlen(s));
             write(1,"\r\n",2);
         };

         /* open the file, or not */

         if ((thefile = open (file, O_RDONLY)) != -1)
      {
        /* printf ("---------------- %s\n", ffblk.ff_name); */
             write(1,"---------------- ",17);
             write(1,longfile, strlen(longfile));
             write(1,"\r\n",2);
        ret = find_str (needle, thefile, invert_search, count_lines, number_output, ignore_case);
        close (thefile);
      }

         else
      {
        s = catgets (cat, 2, 0, "Cannot open file");
        /* printf ("FIND: %s: %s\n", argv[i], s); */
             write(1,"FIND: ",6);
             write(1,argv[i],strlen(argv[i]));
             write(1,": ",2);
             write(1,s,strlen(s));
             write(1,"\r\n",2);
      }

         /* return the cwd */

         chdir (cwd2); /* restore cwd on THAT drive */

         /* _dos_setdrive (drive, &maxdrives); */
         (void) setdisk (drive - 1); /* dir.h */
         chdir (cwd);

         /* find next file to match the filemask */

         /* done = findnext (&ffblk); */
         done = LFNNextFile(file, longfile);
       } /* while !done */

            LFNFindStop();

   } /* for each argv */
    } /* else */

  /* Done */

  catclose (cat);


 /* RETURN: If the string was found at least once, returns 0.
  * If the string was not found at all, returns 1.
  * (Note that find_str.c returns the exact opposite values.)
  */

  exit ( (ret ? 0 : 1) );
  return (ret ? 0 : 1);

}
示例#23
0
int
InitializeFittingMemory (unsigned long size, int HardDiskOk,
			 unsigned long *allocated,
			 /* Needed to check wether a swap file is
			    not created on the source or destination
			    drive: */
			 char sdrv, char tdrv)
{
  char *tempvar = NULL;
  struct dfree free;
  int curdisk, tempdisk, run = 1;
  unsigned long farfree;
  struct IniParserStruct *ParsedData;

  ParsedData = GetParsedData ();

  Initialised = TRUE;
  AmofProcessed = 0;

  CloseFunc = DoNothing;
  PrepareToReadFunc = ResetAmof;
  PrepareToWriteFunc = ResetAmof;

  /* First of all see wether main memory is not large enough */
  farfree = farcoreleft ();
  if (farfree > size)
    {
      FarBlock = (char far *) farmalloc (size);

      LastOffset = FP_OFF (FarBlock);
      LastSegment = FP_SEG (FarBlock);
      SavedSegment = LastSegment = LastSegment + LastOffset / 16;
      SavedOffset = LastOffset = LastOffset % 16;

      MemType = BUFFERS;
      CloseFunc = CloseBuffers;
      ReadFunc = BufferRead;
      WriteFunc = BufferWrite;
      PrepareToReadFunc = PrepareForChangingBuffers;
      PrepareToWriteFunc = PrepareForChangingBuffers;

      *allocated = size;
    }


  /* See wether EMS is installed. */
  if ((!MemType) && ParsedData->UseEMS && ((EMSBase = EMSbaseaddress ()) != 0))
    {
      /* See if there is enough memory. */
      if ((size / 16384) + 1 < EMSpages ())
	{
	  Handle = EMSalloc ((int) (size / 16384) + 1);
	  if (Handle >= 0)
	    {
	      CloseFunc = CloseEMS;
	      WriteFunc = EMSWrite;
	      ReadFunc = EMSRead;
	      MemType = EMS;
	    }

	  *allocated = size;
	}
    }

  /* See wether XMS is installed. */
  if (ParsedData->UseXMS && (!MemType) && XMSinit ())
    {
      /* See if there is enough memory. */
      if (size < XMScoreleft ())
	{
	  Handle = XMSalloc (size);
	  if (Handle != 0)
	    {
	      MemType = XMS;
	      CloseFunc = CloseXMS;
	      WriteFunc = XMSWrite;
	      ReadFunc = XMSRead;
	    }

	  *allocated = size;
	}
    }

  /* See wether the hard disk can be used. */
  if (!MemType && HardDiskOk)
    {
      tempvar = getenv ("temp");
      if (!tempvar)
	tempvar = getenv ("TEMP");
      if (tempvar && tempvar[0])
	strcpy (tempfile, tempvar);
      else
	strcpy (tempfile, "C:\\");

      /* Make sure that the disk where the temporary file is created
         is not either the source of the target of the disk copy.     */
      if ((toupper (tempfile[0]) == toupper (sdrv)) ||
	  (toupper (tempfile[0]) == toupper (tdrv)))
	strcpy (tempfile, "C:\\");

      curdisk = getdisk ();
      tempdisk = toupper (tempfile[0]) - 65;

      /* If the TEMP environment variable doesn't have a path form,
         use the root of c: instead. */
      if ((tempdisk < 0) || (tempdisk > 26) || (tempfile[1] != ':'))
	{
	  strcpy (tempfile, "C:\\");
	  tempdisk = 2;
	}

      for (;;)
	{
	  setdisk (tempdisk);
	  if (getdisk () == tempdisk)
	    {
	      unsigned long total;

	      setdisk (curdisk);

	      getdfree (tempdisk + 1, &free);
	      total = (long) free.df_avail * (long) free.df_bsec *
		(long) free.df_sclus;

	      if (total >= size)
		{
                  char* pSFNSlot;
                  ConvertToSFN(tempfile, ENVVAR_ID);
                  pSFNSlot = GetSFN(ENVVAR_ID);
                  if (pSFNSlot)
                  {
                     strcpy(tempfile, pSFNSlot);
		     Handle = creattemp (tempfile, 0);
		     if (Handle != -1)
		     {
		        MemType = HARDDISK;
		        CloseFunc = CloseDisk;
		        ReadFunc = DiskRead;
		        WriteFunc = DiskWrite;
		        PrepareToReadFunc = PrepareForReadingDisk;
		        PrepareToWriteFunc = PrepareForWritingDisk;
		        *allocated = size;
		        break;
		     }
                  }
		}
	    }
	  if (tempdisk != 2 || run == 1)	/* if not C drive. */
	    {
	      run++;
	      strcpy (tempfile, "C:\\");
	      tempdisk = 2;	/* try C drive instead. */
	    }
	  else
	    break;
	}
    }

  /* See if there is enough memory left on the far heap. */
  if (!MemType && farfree > BUFFERSIZE)
    {
      size = farfree - (farfree % BUFFERSIZE);
      FarBlock = (char far *) farmalloc (size);

      LastOffset = FP_OFF (FarBlock);
      LastSegment = FP_SEG (FarBlock);
      SavedSegment = LastSegment = LastSegment + LastOffset / 16;
      SavedOffset = LastOffset = LastOffset % 16;

      MemType = BUFFERS;
      CloseFunc = CloseBuffers;
      ReadFunc = BufferRead;
      WriteFunc = BufferWrite;
      PrepareToReadFunc = PrepareForChangingBuffers;
      PrepareToWriteFunc = PrepareForChangingBuffers;

      *allocated = size;
    }

  return MemType;
}
示例#24
0
文件: sys.c 项目: TijmenW/FreeDOS
int main(int argc, char **argv)
{
  COUNT drive;                  /* destination drive */
  COUNT drivearg = 0;           /* drive argument position */
  BYTE *bsFile = NULL;          /* user specified destination boot sector */
  unsigned srcDrive;            /* source drive */
  BYTE srcPath[SYS_MAXPATH];    /* user specified source drive and/or path */
  BYTE rootPath[4];             /* alternate source path to try if not '\0' */
  WORD slen;

  printf("FreeDOS System Installer " SYS_VERSION "\n\n");

  if (argc > 1 && memicmp(argv[1], "CONFIG", 6) == 0)
  {
    exit(FDKrnConfigMain(argc, argv));
  }

  srcPath[0] = '\0';
  if (argc > 1 && argv[1][1] == ':' && argv[1][2] == '\0')
    drivearg = 1;

  if (argc > 2 && argv[2][1] == ':' && argv[2][2] == '\0')
  {
    drivearg = 2;
    strncpy(srcPath, argv[1], SYS_MAXPATH - 12);
    /* leave room for COMMAND.COM\0 */
    srcPath[SYS_MAXPATH - 13] = '\0';
    /* make sure srcPath + "file" is a valid path */
    slen = strlen(srcPath);
    if ((srcPath[slen - 1] != ':') &&
        ((srcPath[slen - 1] != '\\') || (srcPath[slen - 1] != '/')))
    {
      srcPath[slen] = '\\';
      slen++;
      srcPath[slen] = '\0';
    }
  }

  if (drivearg == 0)
  {
    printf("Usage: %s [source] drive: [bootsect [BOTH|BOOTONLY]]\n", pgm);
    printf
        ("  source   = A:,B:,C:\\KERNEL\\BIN\\,etc., or current directory if not given\n");
    printf("  drive    = A,B,etc.\n");
    printf
        ("  bootsect = name of 512-byte boot sector file image for drive:\n");
    printf("             to write to *instead* of real boot sector\n");
    printf
        ("  BOTH     : write to *both* the real boot sector and the image file\n");
    printf
        ("  BOOTONLY : do *not* copy kernel / shell, only update boot sector or image\n");
    printf("%s CONFIG /help\n", pgm);
    exit(1);
  }
  drive = toupper(argv[drivearg][0]) - 'A';

  if (drive < 0 || drive >= 26)
  {
    printf("%s: drive %c must be A:..Z:\n", pgm,
           *argv[(argc == 3 ? 2 : 1)]);
    exit(1);
  }

  /* Get source drive */
  if ((strlen(srcPath) > 1) && (srcPath[1] == ':'))     /* src specifies drive */
    srcDrive = toupper(*srcPath) - 'A';
  else                          /* src doesn't specify drive, so assume current drive */
  {
#ifdef __TURBOC__
    srcDrive = (unsigned) getdisk();
#else
    _dos_getdrive(&srcDrive);
    srcDrive--;
#endif
  }

  /* Don't try root if src==dst drive or source path given */
  if ((drive == srcDrive)
      || (*srcPath
          && ((srcPath[1] != ':') || ((srcPath[1] == ':') && srcPath[2]))))
    *rootPath = '\0';
  else
    sprintf(rootPath, "%c:\\", 'A' + srcDrive);

  if ((argc <= drivearg + 2)
      || (memicmp(argv[drivearg + 2], "BOOTONLY", 8) != 0))
  {
    if (!check_space(drive, oldboot))
    {
      printf("%s: Not enough space to transfer system files\n", pgm);
      exit(1);
    }

    printf("\nCopying KERNEL.SYS...\n");
    if (!copy(drive, srcPath, rootPath, "KERNEL.SYS"))
    {
      printf("\n%s: cannot copy \"KERNEL.SYS\"\n", pgm);
      exit(1);
    }
  } /* copy kernel */

  if (argc > drivearg + 1)
    bsFile = argv[drivearg + 1];
    
  printf("\nWriting boot sector...\n");
  put_boot(drive, bsFile,
           (argc > drivearg + 2)
           && memicmp(argv[drivearg + 2], "BOTH", 4) == 0);

  if ((argc <= drivearg + 2)
      || (memicmp(argv[drivearg + 2], "BOOTONLY", 8) != 0))
  {
    printf("\nCopying COMMAND.COM...\n");
    if (!copy(drive, srcPath, rootPath, "COMMAND.COM"))
    {
      char *comspec = getenv("COMSPEC");
      if (comspec != NULL)
      {
        printf("%s: Trying \"%s\"\n", pgm, comspec);
        if (!copy(drive, comspec, NULL, "COMMAND.COM"))
          comspec = NULL;
      }
      if (comspec == NULL)
      {
        printf("\n%s: cannot copy \"COMMAND.COM\"\n", pgm);      
        exit(1);
      }
    }
  } /* copy shell */

  printf("\nSystem transferred.\n");
  return 0;
}
CLIPPER getdrive()
{
    _retni(getdisk());
}
示例#26
0
文件: dir.c 项目: TijmenW/FreeDOS
/*
 * dir_print_header
 *
 * print the header for the dir command
 */
int dir_print_header(int drive)
{
	/* one byte alignment */
#pragma -a-
  struct media_id
  {
    int info_level;
    int serial1;
    int serial2;
    char vol_id[11];
    char file_sys[8];
  }
  media;
	/* standard alignment */
#pragma -a.
  struct ffblk f;
  struct SREGS s;
  union REGS r;
  int currDisk;
  int rv;

  if (cbreak)
    return E_CBreak;

  if (optB)
    return 0;

  currDisk = getdisk();
  if(changeDrive(drive+1) != 0) {
    setdisk(currDisk);
    return 1;
  }

  /* get the media ID of the drive */
/*
   Format of disk info:
   Offset  Size    Description     (Table 01766)
   00h    WORD    0000h (info level)
   02h    DWORD   disk serial number (binary)
   06h 11 BYTEs   volume label or "NO NAME    " if none present
   11h  8 BYTEs   (AL=00h only) filesystem type (see #01767)

 */

  r.x.ax = 0x6900;
  r.x.bx = drive + 1;
  s.ds = FP_SEG(&media);
  r.x.dx = FP_OFF(&media);
  int86x(0x21, &r, &r, &s);

  /* print drive info */
  printf("\n Volume in drive %c", drive + 'A');

  if (FINDFIRST("\\*.*", &f, FA_LABEL) == 0)
  {
        /* Added to remove "." from labels which are longer than
               8 characters (as DOS does). */
    char *dotptr = strchr(f.ff_name, '.');
    if (dotptr != NULL)
    	if(strlen(dotptr + 1))
			memmove(dotptr, dotptr + 1, strlen(dotptr));
		else *dotptr = '\0';		/* dot at end of name */
    printf(" is %s\n", f.ff_name);
  }
  else
  {
    printf(" has no label\n");
  }

  setdisk(currDisk);

  if ((rv = incline()) == 0) {

  /* print the volume serial number if the return was successful */
  if (!r.x.cflag)
  {
    printf(" Volume Serial Number is %04X-%04X\n", media.serial2, media.serial1);
    rv = incline();
  }
  }

        /* Added to exactly match DOS's formatting. */
  if ( (optS) && (rv == 0) ) {
      printf("\n");
      rv = incline();
  }

  return rv;
}
SaveDir::SaveDir()
{
    drive = getdisk();
    path[0] = '\\';
    getcurdir( 0, path+1 );
}
示例#28
0
文件: STATUS.C 项目: kytulendu/TW
void writedriveno( void ) {
	dispstrhgc( "ä´Ã¿ì  :", 40, 0, NORMALATTR );
	prchar( 'A' + getdisk( ), BOLDATTR, 45, NORMALATTR );
}
示例#29
0
void main(int argc,char *argv[])
{
    char *basedir, *p;
    FILEFINDBUF3 find; HDIR dirhandle; ULONG srch_cnt;
    int newdrive, urdrive, rootdir, dotdir, dotdotdir;
    int asking=TRUE, retcode=TRUE;

    while (--argc)  {
	++argv;
	if ((argv[0][0] == '/') || (argv[0][0] == '-')) {
	    switch(toupper(argv[0][1])) {
		case 'Y': asking = FALSE; break;

#ifdef __OS2__
		case 'F': forcedel = 1; break;
#endif
		default : printf("Invalid switch - %c\n", argv[0][1]); abort();
		}
	    }
	else
	    break;
	}
    if (!argc) {
	puts("DELTREE2 v1.0\nRequired parameter missing");
	abort();
	}
    urdrive = getdisk();
#ifdef __OS2__
    DosError(FERR_DISABLEHARDERR);
#endif

    /* Process each command line parameter */
    while (argc--) {
	basedir = *argv++;
	if (asking) {
	    printf("Delete directory \"%s\" and all its subdirectories? [yn] ",
		   basedir);
	    if (!getyn())
		continue;
	    }
	setdisk(urdrive);
	srch_cnt = 1; dirhandle = HDIR_CREATE;
	findret = DosFindFirst(basedir, &dirhandle, MUST_HAVE_DIRECTORY,
			       &find, sizeof(find), &srch_cnt,
			       FIL_STANDARD);
	if (findret == 0) {
#ifndef __OS2__
	dirhandle = 1;
#endif
	    DosFindClose(dirhandle);
	    }
	else
	    continue;  /* no such directory, goto next argument */
	if (basedir[1] == ':') {
	    /* Need to change drives */
	    newdrive = toupper(basedir[0])-'A';
	    if (newdrive != urdrive) {
		setdisk(newdrive);
		if (newdrive != getdisk())
		    continue;  /* cannot switch drives, goto next argument */
	       }
	    basedir+=2;
	    }
	assert (NULL != (p=getcwd(NULL, MAXPATH)));
	dotdir = !strcmp(basedir, ".") ||
		 !strcmp(basedir, p+2);
	free(p);
	dotdotdir = !strcmp(basedir, "..");
	rootdir = (!strcmp(basedir,"\\") ||
		   !strcmp(basedir,"/"));
	printf("Deleting %s...\n", basedir);
	if (rootdir) {
	    CHDIR("\\");
	    retcode &= nextdir(FALSE);
	    }
	else if (dotdir) {
	    retcode &= nextdir(FALSE);
	    }
	else if (dotdotdir) {
	    CHDIR("..");
	    retcode &= nextdir(FALSE);
	    }
	else {
	    if (CHDIR(basedir))
		continue /* cannot change directory - goto next argument */;
	    retcode &= nextdir(FALSE);
	    CHDIR("..");
#ifndef DBG
	    retcode &= (0 == DosDeleteDir(basedir));
#endif
	    }
	/* goto next argument */
	}
    setdisk(urdrive);
    exit(retcode ? 0 : 1);
    }
示例#30
0
文件: dir.c 项目: TijmenW/FreeDOS
/*
 * dir_print_header
 *
 * print the header for the dir command
 */
int dir_print_header(int drive)
{
#pragma -a-
  struct media_id
  {
    int info_level;
    int serial1;
    int serial2;
    char vol_id[11];
    char file_sys[8];
  }
  media;
#pragma -a.
  struct REGPACK r;
  struct ffblk f;
  int disk;
  int rv;

  if (cbreak)
    return E_CBreak;

  if (optB)
    return 0;

  disk = getdisk();
  if(changeDrive(drive + 1) != 0)
  	return 1;

  /* get the media ID of the drive */
/*
   Format of disk info:
   Offset  Size    Description     (Table 01766)
   00h    WORD    0000h (info level)
   02h    DWORD   disk serial number (binary)
   06h 11 BYTEs   volume label or "NO NAME    " if none present
   11h  8 BYTEs   (AL=00h only) filesystem type (see #01767)

 */

  r.r_ax = 0x6900;
  r.r_bx = 0;
  r.r_ds = FP_SEG(&media);
  r.r_dx = FP_OFF(&media);
  intr(0x21, &r);

  /* print drive info */
  printf("\n Volume in drive %c", drive + 'A');

  if (FINDFIRST("\\*.*", &f, FA_LABEL) == 0)
  {
    printf(" is %s\n", f.ff_name);
  }
  else
  {
    printf(" has no label\n");
  }

  setdisk(disk);

  if ((rv = incline()) == 0) {
	  /* print the volume serial number if the return was successful */
	  if (!r.r_flags & 1)
	  {
		printf(" Volume Serial Number is %04X-%04X\n"
		 , media.serial2, media.serial1);
		rv = incline();
	  }
  }

  return rv;
}