Пример #1
0
void Fatal ()
// fatal error, attempt to shut down and exit
// if we already tried to shut down -- just abort without doing anything
{
	static BOOL fTwice;
	if (!fTwice) {
		fTwice = TRUE;
		if (pnmBsc) pnmBsc->close();
		if (pdbBsc) {
			pdbBsc->Close();	// do not commit!

			// see if we should delete
			if (fDeleteOnFatal && OutputFileName) {
				_unlink(OutputFileName);
			}
			else // restore the file time if possible...
			if (OutputFileName && sbufBsc.st_atime && sbufBsc.st_mtime) {
				struct _utimbuf ubuf;
				ubuf.actime  = sbufBsc.st_atime;
				ubuf.modtime = sbufBsc.st_mtime;
				_utime(OutputFileName, &ubuf);
			}
		}
	}
	exit(4);
}
Пример #2
0
int my_dirent_utime(const char *path, time_t mtime)
{
	struct _utimbuf ut;
	ut.actime = mtime;
	ut.modtime = mtime;
	return _utime(path, &ut);
}
Пример #3
0
int SyncTransferThread::do_touch_local_file_with_time(QString fileName, QDateTime time)
{
    // Linux 上可以使用 utime 或者 utimes 函数, - change file last access and modification times
    // Windows 上文件 SetFileTime()函数设置文件的创建时间、最近一次访问时间以及最近一次修改的时间等
    // Windows 目录 两个函数GetDirTime()和SetDirTime()来实现对文件夹时间信息
    // Qt 中好像是没有修改文件时间属性的方法。

    int ret;
    QFileInfo fi(fileName);

#ifdef WIN32
    // method 1, ok
    QFile q_file(fileName);
    if (!q_file.open(QIODevice::ReadWrite)) {
        q_debug()<<"open file error:"<<q_file.errorString();
    } else {
        int fp = q_file.handle();
        struct _utimbuf ub;
        ub.actime = fi.lastRead().toTime_t();
        ub.modtime = time.toTime_t();
        ret = _futime(fp, &ub);
        q_debug()<<"_futime ret: "<<ret<<fileName
                 <<strerror(ret);
        q_file.close();
    }
    return 0;

    // method 2, english ok, chinese faild
    const char *filePathName = gOpt->locale_codec->fromUnicode(QDir::toNativeSeparators(fileName)).constData();
    struct _utimbuf ub;
    ub.actime = fi.lastRead().toTime_t();
    ub.modtime = time.toTime_t();
    ret = _utime(filePathName, &ub);
    q_debug()<<"_utime ret: "<<ret<<filePathName<<fileName
             <<strerror(ret);
    return 0;

    // method 2, english ok, chinese faild
    QString appPath = QCoreApplication::applicationDirPath();
    QString procFilePath = appPath + "/touch.exe";
    QStringList args;
    args<<"-m";
    args<<"-t";
    args<<time.toString("yyyyMMddhhmm.ss");
    args<<QDir::toNativeSeparators(fileName);
    q_debug()<<args;
    QProcess proc;
    proc.start(procFilePath, args);
    ret = proc.waitForFinished();

#else
    struct timeval tv[2] = {{0,0}, {0,0}};
    tv[0].tv_sec = fi.lastRead().toTime_t();
    tv[1].tv_sec = time.toTime_t();
    ret = utimes(GlobalOption::instance()->locale_codec->fromUnicode(fileName), tv);
    assert(ret == 0);    
#endif

    return 0;
}
Пример #4
0
static int _sys_set_time(char *filename, time_t timestamp)
{
  struct _utimbuf timbuf;
  timbuf.actime = timestamp;
  timbuf.modtime = timestamp;
  return _utime(filename, &timbuf);
}
Пример #5
0
/* set modtime on file */
int
_afsconf_Touch(struct afsconf_dir *adir)
{
    char *cellservDB;
    int code;
#ifndef AFS_NT40_ENV
    struct timeval tvp[2];
#endif

    adir->timeRead = 0;		/* just in case */
    adir->timeCheck = 0;

    _afsconf_CellServDBPath(adir, &cellservDB);
    if (cellservDB == NULL)
	return ENOMEM;

#ifdef AFS_NT40_ENV
    code = _utime(cellservDB, NULL);
#else
    gettimeofday(&tvp[0], NULL);
    tvp[1] = tvp[0];
    code = utimes(cellservDB, tvp);
#endif /* AFS_NT40_ENV */
    free(cellservDB);

    return code;
}
Пример #6
0
int filecache_retrieve(TARGET *t, MD5SUM buildmd5sum)
{
	MD5SUM blobmd5sum;
	MD5SUM copymd5sum;
	time_t time;

	/* if the target is available in the cache */
	const char *cachedname = filecache_getfilename(t, buildmd5sum, 0);
	if (!cachedname)
		return 0;

	if (!filecache_findlink(cachedname, blobmd5sum))
	{
		if( DEBUG_MD5HASH)
		{
			printf("Cannot find %s in cache as %s\n", t->name, cachedname);
			filecache_disable(t);
		}
		return 0;
	}

	getcachedmd5sum( t, 1 );

	if ( file_time( t->boundname, &time ) == 0 )
	{
		if (memcmp(blobmd5sum, t->contentmd5sum, sizeof(MD5SUM)) == 0)
		{
			if (!(t->flags & T_FLAG_NOCARE))
#ifdef _MSC_VER
				_utime(t->boundname, NULL);
#else
				utime(t->boundname, NULL);
#endif
			printf("%s is already the proper cached target.\n", t->name);
			return 1;
		}
	}

	cachedname = filecache_getfilename(t, blobmd5sum, ".blob");

	/* try to get it from the cache */
	if (copyfile(t->boundname, cachedname, &copymd5sum)  &&  memcmp(copymd5sum, blobmd5sum, sizeof(MD5SUM)) == 0)
	{
		printf( "Using cached %s\n", t->name );
		return 1;
	}
	else if (!(t->flags & T_FLAG_OPTIONALFILECACHE))
	{
		printf( "Cannot retrieve %s from cache (will build normally)\n", t->name );
		return 0;
	}

	if( DEBUG_MD5HASH)
	{
		printf( "Cannot find %s in cache as %s\n", t->name, cachedname );
	}

	return 0;
}
Пример #7
0
void file_touch(const char *filename)
{
#ifdef BAM_FAMILY_WINDOWS
    _utime(filename, NULL);
#else
    utime(filename, NULL);
#endif
}
Пример #8
0
extern int
utime(const char* path, const struct utimbuf* ut)
{
	int	r;
	int	oerrno;
	char	buf[PATH_MAX];

	oerrno = errno;
	if ((r = _utime(path, ut)) && errno == ENOENT && execrate(path, buf, sizeof(buf), 0))
	{
		errno = oerrno;
		r = _utime(path = buf, ut);
	}
	if (!r)
		ctime_now(path);
	return r;
}
Пример #9
0
/*
** Set a file time stamp.
*/
void SetFileTime(const char *path, Int32 time)
{
  struct utimbuf stime;
  stime.modtime=stime.actime=time;
#if DT_OS == 'o' && DT_CC != 'b'
  _utime(path, &stime);
#else
  utime(path, &stime);
#endif
}
Пример #10
0
int utimes(char* file_Name,struct timeval file_Time[])
{
	struct _utimbuf file_Utime;

	/* Fill out the structure */
	file_Utime.actime = file_Time[0].tv_sec;
	file_Utime.modtime = file_Time[1].tv_sec;

	/* And call utime() */
	return _utime(file_Name,&file_Utime);
}
Пример #11
0
int NXLFSMessageCache::cfcleanup()
{
  NXMutexLocker ml(m_mutex, "cfcleanup", "n/a");

  char p[MAX_PATH];
  int r = 0;

  clock_t start = clock();

  //--- touch recently used cache files ---
  for(CF* f = m_files; f; f = f->n)
  {
    if(!f->c) break;
    if(sprintf_s(p, "%s\\%s\\%X\\%s", m_cache, "msg", f->s, f->d) == -1) { r = R(-11, "buffer error"); continue; }

    _utimbuf tb;
    tb.actime = tb.modtime = f->t;
    if(_utime(p, &tb)) r = R(-21, "utime error");
  }

  //--- remove cache files over limit ---
  __int64 s = m_maxdisk;
  for(CF* f = m_files; f; f = f->n)
  {
    s -= f->z;
    if(s < 0)
    {
      CF* c = f->n;
      f->n = NULL;
      ml.unlock(); // todo: what if someone fetches an article delete in a few nanos? stop worrying

      for(CF* d = c; d; d = d->n)
      {
        if(sprintf_s(p, "%s\\%s\\%X\\%s", m_cache, "msg", d->s, d->d) == -1) { r = R(-21, "buffer error"); continue; }
        if(_unlink(p)) { r = R(-21, "unlink error"); continue; }
        if(NXLOG.cache > 1)
          printf("cache:\tcleanup %s\n", d->d);
      }
      delete c; 
    }
  }

  clock_t end = clock();
  if(NXLOG.cache)
    printf("cache:\tcleanup took %.2fsec\n", (double)(end-start)/CLOCKS_PER_SEC);

  return r;
}
Пример #12
0
bool XLFileUtil::setfiletime(const std::string & inFileName,time_t now)
{
#if _MSC_VER
	struct _utimbuf val;
#else
	struct utimbuf val;
#endif
	val.actime = now;
	val.modtime = now;
#if _MSC_VER
	int r = _utime(inFileName.c_str(),&val);
#else
	int r = utime(inFileName.c_str(),&val);
#endif
	return (r == 0);
}
Пример #13
0
OsStatus OsFileWnt::touch()
{
    OsStatus stat = OS_INVALID;

    if (exists() == OS_SUCCESS)
    {
        if (_utime(mFilename,NULL) == 0)
            stat = OS_SUCCESS;
    }
    else
    {
        stat = open(CREATE);
        close();
    }

    return stat;
}
Пример #14
0
    void setFileTime(const char *filename, time_t *inaccessedtime, time_t *increatedtime, time_t *inmodifiedtime) // params NULL if not to be set
    {
        // only supports accessed and modified currently
        struct _utimbuf am;
        if (!inaccessedtime||!inmodifiedtime) {
            struct stat info;
            if (stat(filename, &info) != 0)
                return;
            am.actime = info.st_atime;
            am.modtime = info.st_mtime;
        }
        if (inaccessedtime)
            am.actime   = *inaccessedtime;
        if (inmodifiedtime)
            am.modtime  = *inmodifiedtime;
        _utime(filename, &am);

    }
Пример #15
0
/* set modtime on file */
static int
afsconf_Touch(struct afsconf_dir *adir)
{
    char tbuffer[256];
#ifndef AFS_NT40_ENV
    struct timeval tvp[2];
#else
    char *p;
#endif

    adir->timeRead = 0;		/* just in case */

#ifdef AFS_NT40_ENV
    /* NT client CellServDB has different file name than NT server or Unix */

    if (IsClientConfigDirectory(adir->name)) {
	if (!afssw_GetClientCellServDBDir(&p)) {
	    strcompose(tbuffer, sizeof(tbuffer), p, "/",
		       AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
	    free(p);
	} else {
	    int len = (int)strlen(tbuffer);
	    if (tbuffer[len - 1] != '\\' && tbuffer[len - 1] != '/') {
		strncat(tbuffer, "\\", sizeof(tbuffer));
	    }
	    strncat(tbuffer, AFSDIR_CELLSERVDB_FILE_NTCLIENT,
		    sizeof(tbuffer));
	    tbuffer[sizeof(tbuffer) - 1] = '\0';
	}
    } else {
	strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
		   NULL);
    }

    return _utime(tbuffer, NULL);

#else
    strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
    gettimeofday(&tvp[0], NULL);
    tvp[1] = tvp[0];
    return utimes(tbuffer, tvp);
#endif /* AFS_NT40_ENV */
}
Пример #16
0
static Boolean _setfileTime( const char* filename, long filetime ) {
#if defined _WIN32
  struct _utimbuf aTimeBuf;
  aTimeBuf.actime  = filetime;
  aTimeBuf.modtime = filetime;
  _convertPath2OSType( filename );
  if( _utime( filename, &aTimeBuf ) == 0)
#else
  struct utimbuf aTimeBuf;
  aTimeBuf.actime  = filetime;
  aTimeBuf.modtime = filetime;
  _convertPath2OSType( filename );
  if( utime( filename, &aTimeBuf ) == 0 )
#endif
    return True;
  else {
    TraceOp.terrno( name, TRCLEVEL_EXCEPTION, __LINE__, 9999, errno, "Error utime file [%s]",
                   filename );
    return False;
  }
}
Пример #17
0
int checksum_retrieve(TARGET *t, MD5SUM buildmd5sum)
{
	CHECKSUMDATA cachedata, *c = &cachedata;
	char buildmd5sumstring[33];

	checksums_readfile();

	strcpy(buildmd5sumstring, md5tostring(buildmd5sum));
	c->boundname = buildmd5sumstring;

	if (!hashcheck(checksumhash, (HASHDATA **)&c)) {
		return 0;
	}

	getcachedmd5sum(t, 0);

	if (t->contentchecksum  &&  t->contentchecksum->mtime != 0  &&  memcmp( c->contentmd5sum, t->contentchecksum->contentmd5sum, MD5_SUMSIZE ) == 0 )
	{
		time_t time;
#ifdef _MSC_VER
		_utime(t->boundname, NULL);
#else
		utime(t->boundname, NULL);
#endif
		file_time(t->boundname, &time);
		t->contentchecksum->mtime = time;
		t->contentchecksum->age = 0;
		checksumsdirty = 1;

		//printf("JAMDEBUG: %s is already the proper cached target.\n", t->name);
		return 1;
	}
	else
	{
		memset(&c->contentmd5sum, 0, MD5_SUMSIZE);
	}

	return 0;
}
Пример #18
0
int utime(char *file, void *newTimes) {
#if !CAM_DRYOS
  return _utime(file, newTimes);
#else
 int res=0;
 int fd;
 fd = _open(file, 0, 0);

#ifdef CAM_DRYOS_2_3_R39
   if (fd>=0) {
       _close(fd);
       res=_SetFileTimeStamp(file, ((int*)newTimes)[0] , ((int*)newTimes)[1]);
   }
#else
     if (fd>=0) {
      res=_SetFileTimeStamp(fd, ((int*)newTimes)[0] , ((int*)newTimes)[1]);
      _close(fd);
     }
     // return value compatibe with utime: ok=0 fail=-1
#endif
  return (res)?0:-1;
#endif
}
Пример #19
0
afs_int32
SBOZO_Install(struct rx_call *acall, char *aname, afs_int32 asize, afs_int32 mode, afs_int32 amtime)
{
    afs_int32 code;
    int fd;
    afs_int32 len;
    afs_int32 total;
#ifdef AFS_NT40_ENV
    struct _utimbuf utbuf;
#else
    struct timeval tvb[2];
#endif
    char filepath[AFSDIR_PATH_MAX], tbuffer[AFSDIR_PATH_MAX], *fpp;
    char caller[MAXKTCNAMELEN];

    if (!afsconf_SuperUser(bozo_confdir, acall, caller))
	return BZACCESS;
    if (bozo_isrestricted)
	return BZACCESS;

    /* construct local path from canonical (wire-format) path */
    if (ConstructLocalBinPath(aname, &fpp)) {
	return BZNOENT;
    }
    strcpy(filepath, fpp);
    free(fpp);

    if (DoLogging)
	bozo_Log("%s is executing Install '%s'\n", caller, filepath);

    /* open file */
    fpp = filepath + strlen(filepath);
    strcpy(fpp, ".NEW");	/* append ".NEW" to end of filepath */
    fd = open(filepath, O_CREAT | O_RDWR | O_TRUNC, 0777);
    if (fd < 0)
	return errno;
    total = 0;
    while (1) {
	len = rx_Read(acall, tbuffer, sizeof(tbuffer));
	if (len < 0) {
	    close(fd);
	    unlink(filepath);
	    return 102;
	}
	if (len == 0)
	    break;		/* no more input */
	code = write(fd, tbuffer, len);
	if (code != len) {
	    close(fd);
	    unlink(filepath);
	    return 100;
	}
	total += len;		/* track total written for safety check at end */
    }
    close(fd);
    if (asize != total) {
	unlink(filepath);
	return 101;		/* wrong size */
    }

    /* save old files */
    *fpp = '\0';		/* remove ".NEW" from end of filepath */
    SaveOldFiles(filepath);	/* don't care if it works, still install */

    /* all done, rename to final name */
    strcpy(tbuffer, filepath);
    strcat(tbuffer, ".NEW");
    code = (rk_rename(tbuffer, filepath) ? errno : 0);

    /* label file with same time for our sanity */
#ifdef AFS_NT40_ENV
    utbuf.actime = utbuf.modtime = amtime;
    _utime(filepath, &utbuf);
#else
    tvb[0].tv_sec = tvb[1].tv_sec = amtime;
    tvb[0].tv_usec = tvb[1].tv_usec = 0;
    utimes(filepath, tvb);
#endif /* AFS_NT40_ENV */

    if (mode)
	chmod(filepath, mode);

    if (code < 0) {
	osi_auditU(acall, BOS_InstallEvent, code, AUD_STR, filepath, AUD_END);
	return errno;
    } else
	return 0;
}
Пример #20
0
Файл: fs.c Проект: Cahya/node
void fs__utime(uv_fs_t* req, const char* path, double atime, double mtime) {
  int result;
  struct _utimbuf b = {(time_t)atime, (time_t)mtime};
  result = _utime(path, &b);
  SET_REQ_RESULT(req, result);
}
Пример #21
0
int _RTL_FUNC _utime32 (const char * path, struct utimbuf * times)
{
    return _utime(path, times);
}
Пример #22
0
int unZ(char *archiveFilename, char *extractPath)
{
	FILE *fp;
	fchunk_t fc;

	unsigned int i, destsize;
	unsigned char header[256], *toc;

	unsigned int numFiles, compsize, tocOffset, tocSize, numDirs;
	direntry_t *dirs;

	destsize = strlen(extractPath);

	fp = fopen(archiveFilename, "rb");

	if (!fp)
	{
		printf("Error opening %s!\n", archiveFilename);
		return;
	}

	fseek(fp, 0, SEEK_END);
	compsize = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	fread(header, 256, 1, fp);

	// check signature
	if (GET_UI32(header) != 0x8C655D13)
	{
		printf("Archive corrupt: Bad signature!\n");
		return 0;
	}

	//numFiles = GET_UI16(header + 12);

	// check size
	if (compsize != GET_UI32(header + 18))
	{
		printf("Archive corrupt: Incorrect size!\n");
		return 0;
	}

	// read toc
	tocOffset = GET_UI32(header + 41);
	tocSize = compsize - tocOffset;

	toc = malloc(tocSize);
	fseek(fp, tocOffset, SEEK_SET);
	fread(toc, 1, tocSize, fp);
	tocOffset = 0;


	// parse dirs
	numDirs = GET_UI16(header + 49);
	dirs = malloc(sizeof(*dirs) * numDirs);

	for (i = 0; i < numDirs; i++)
	{
		unsigned int dir_numFiles  = GET_UI16(toc + tocOffset);
		unsigned int dir_entrySize = GET_UI16(toc + tocOffset + 2);
		unsigned int dir_nameSize  = GET_UI16(toc + tocOffset + 4);

		dirs[i].name = malloc(destsize + 1 + dir_nameSize + 1);
		strcpy(dirs[i].name, extractPath);
		dirs[i].name[destsize] = '\\';
		memcpy(dirs[i].name + destsize + 1, toc + tocOffset + 6, dir_nameSize);
		dirs[i].name[destsize + 1 + dir_nameSize] = '\0';
		dirs[i].numFiles = dir_numFiles;

		tocOffset += dir_entrySize;
	}

	// parse and save files
	fseek(fp, 255, SEEK_SET);
	fc.fp = fp;
	for (i = 0; i < numDirs; i++)
	{
		unsigned int dir_nameSize;
		int j;

		_mkdir(extractPath);
		if (dirs[i].name[0])
			_mkdir(dirs[i].name);

		printf("Dir %s, %d files\n", dirs[i].name, dirs[i].numFiles);
		dir_nameSize = strlen(dirs[i].name);

		for (j = 0; j < dirs[i].numFiles; j++)
		{
			FILE *fpw;
			int blastErr;

			unsigned int file_decompressedSize = GET_UI32(toc + tocOffset + 3);
			unsigned int file_compressedSize   = GET_UI32(toc + tocOffset + 7);
			unsigned int file_modifiedDate     = GET_UI16(toc + tocOffset + 15);
			unsigned int file_modifiedTime     = GET_UI16(toc + tocOffset + 17);
			unsigned int file_entrySize        = GET_UI16(toc + tocOffset + 23);
			unsigned int file_nameSize         = toc[tocOffset + 29];

			char *filename;

			struct tm tmm;
			struct _utimbuf ut;

			filename = malloc(dir_nameSize + file_nameSize + 2);
			strcpy(filename, dirs[i].name);
			filename[dir_nameSize] = '\\';
			strncpy(filename + dir_nameSize + 1, toc + tocOffset + 30, file_nameSize);
			filename[dir_nameSize + 1 + file_nameSize] = '\0';

			printf("%s, %d bytes, %.3f%%\n", filename, file_decompressedSize, (float)file_compressedSize / file_decompressedSize * 100.0f);

			memset(&tmm, 0, sizeof(tmm));
			tmm.tm_year = ( file_modifiedDate           >> 9) + 80;
			tmm.tm_mon  = ((file_modifiedDate & 0x01E0) >> 5) - 1;
			tmm.tm_mday =   file_modifiedDate & 0x001F;
			tmm.tm_hour =   file_modifiedTime           >> 11;
			tmm.tm_min  =  (file_modifiedTime & 0x07E0) >> 5;
			tmm.tm_sec  =  (file_modifiedTime & 0x001F) * 2;

#if defined(SHOWTIME)
			printf("last modified %d %s %d %02d:%02d:%02d\n", 
				tmm.tm_year + 1900, months[tmm.tm_mon], tmm.tm_mday, tmm.tm_hour, tmm.tm_min, tmm.tm_sec);
#endif

			tocOffset += file_entrySize;

			fpw = fopen(filename, "wb");
			fc.size = file_compressedSize;

			blastErr = blast(inf, &fc, outf, fpw);

			if (blastErr == 1)
				printf("Error writing file!\n");
			else if (blastErr != 0)
				printf("Archive corrupt: Error decompressing, trying to continue");

			fclose(fpw);

			ut.actime = time(NULL);
			ut.modtime = mktime(&tmm);
			_utime(filename, &ut);

			free(filename);
		}
	}

	fclose(fp);

	for (i = 0; i < numDirs; i++)
		free(dirs[i].name);

	free(dirs);
	free(toc);

	return 0;
}
Пример #23
0
Файл: C.c Проект: mattn/C-win32
int main(int argc, char** argv)
{
  int ret;
  
  setup_dir();
  
  /* init globals */
  gcc = sa_concat(gcc, "gcc"); /* replaced laterwards if c++ */
  gcc = sa_concat(gcc, "-I.");
  
  src_lines =
    sa_concat(src_lines,
	      "#define __LARGE_C__ " VERSION_INT_STR "\n"
	      "#ifdef __cplusplus\n"
	      "extern \"C\" {\n"
	      "#endif\n"
	      "#include <stdio.h>\n"
	      "#include <stdlib.h>\n"
	      "#ifdef __cplusplus\n"
	      "}\n"
	      "#include <iostream>\n"
	      "using namespace std;\n"
	      "#endif\n"
	      "\n"
	      "__LARGE_C_PREFIX__\n");
  
  argv++;
  { /* parse args, determine cache dir */
    char** new_argv = parse_args(argv, NULL, 0);
    for (; argv != new_argv; argv++) {
      add_spec(*argv, strlen(*argv) + 1);
    }
    if (! keep_files && (oneliner || *argv != NULL)) {
      struct stat st;
      if (oneliner) {
	build_store_dir();
      } else if (stat(*argv, &st) == 0) {
	add_spec(*argv, strlen(*argv) + 1);
	add_spec(&st.st_size, sizeof(st.st_size));
	add_spec(&st.st_mtime, sizeof(st.st_mtime));
	build_store_dir();
      }
    }
  }
  
  /* use cache if possible */
  if (store_dir != NULL && check_specs()) {
    char** child_argv = NULL;
#ifdef _WIN32
    _utime(store_dir, NULL); /* update mtime of the directory */
#else
    utimes(store_dir, NULL); /* update mtime of the directory */
#endif
    exec_file = str_concat(str_dup(store_dir), "/"A_OUT);
    child_argv = sa_concat(child_argv, exec_file);
#ifdef _WIN32
    {
      int status;
	  ret = spawn_w32(child_argv, &status);
      if (status == 0) exit(ret);
    }
#else
    execv(exec_file, child_argv);
#endif
    // if execv failed, we compile
    free(exec_file);
    remove_dir(store_dir);
  }
  
  /* prepare files */
  make_temp_dir();
  exec_file = str_concat(str_dup(temp_dir), "/"A_OUT);
  c_file = str_concat(str_dup(temp_dir), "/source.c");
  if ((src_fp = fopen(c_file, "wt")) == NULL) {
    cmd_error("failed to create temporary file: %s : %s\n", c_file,
	      strerror(errno));
  }
  while (src_lines != NULL && *src_lines != NULL) {
    fputs(*src_lines++, src_fp);
  }
  
  /* write source with adjustments */
  if (! oneliner) {
    FILE* fp;
    char* file;
    char* line;
    int line_no = 0;
    if (argv[0] == NULL) {
      fp = stdin;
      file = "stdin";
    } else if (strcmp(argv[0], "-") == 0) {
      fp = stdin;
      argv++;
      file = "stdin";
    } else {
      file = *argv++;
      if ((fp = fopen(file, "rt")) == NULL) {
	cmd_error("cannot open file: %s : %s\n", file, strerror(errno));
      }
      fprintf(src_fp, "# 1 \"%s\" 1\n", file);
    }
    while ((line = get_line(fp)) != NULL) {
      int comment_out = 0;
      line_no++;
      if (line_no == 1 && strncmp(line, "#!", 2) == 0) {
	comment_out = 1;
      } else if (line[0] == '#') {
	char* buf = str_dup(line + 1);
	char** tokens = split_tokens(buf);
	if (*tokens != NULL) {
	  if (strcmp(tokens[0], "option") == 0) {
	    parse_args(tokens + 1, file, line_no);
	    comment_out = 1;
	  }
	}
	free(buf);
	free(tokens);
      }
      if (comment_out == 1) {
	fprintf(src_fp, "// ");
      }
      fputs(line, src_fp);
    }
    fputs("\n", src_fp);
    if (fp != stdin) {
      fclose(fp);
    }
  }
  
  /* close source file */
  fputs("__LARGE_C_SUFFIX__\n", src_fp);
  fclose(src_fp);
  src_fp = NULL;
  
  /* compile */
  if (use_plusplus) {
    gcc[0] = "g++";
  }
  if (use_main) {
    gcc = sa_concat(gcc, "-D__LARGE_C_PREFIX__=");
    gcc = sa_concat(gcc, "-D__LARGE_C_SUFFIX__=");
  } else {
    gcc =
      sa_concat(gcc, "-D__LARGE_C_PREFIX__=int main(int argc, char** argv) {");
    gcc = sa_concat(gcc, "-D__LARGE_C_SUFFIX__=; return 0; }");
  }
  gcc = sa_concat(gcc, "-o");
  gcc = sa_concat(gcc, show_disassembly ? "-" : exec_file);
  gcc = sa_concat(gcc, c_file);
  gcc = sa_merge(gcc, lopts);
  if ((ret = call_proc(gcc, "could not execute compiler")) != 0) {
    cleanup();
    exit(ret);
  }
  
  if (show_disassembly) {
    cleanup();
    exit(0);
  }
  
  { /* execute */
    char** child_argv = NULL;
    if (use_debugger) {
      child_argv = sa_concat(child_argv, "gdb");
    }
    child_argv = sa_concat(child_argv, exec_file);
    child_argv = sa_merge(child_argv, argv);
    ret = call_proc(child_argv, "could not spawn child process");
  }
  
  /* move temp_dir to store_dir, if possible.
   * or, remove work_dir
   */
  if (store_dir == NULL) {
    cleanup();
  } else {
    save_specs();
    update_cache();
    if (rename(temp_dir, store_dir) != 0) {
      cleanup();
    }
  }
  
  return ret;
}
Пример #24
0
bool extract_file(CTar32CmdInfo &cmdinfo, CTar32 *pTarfile, const char *fname,std::vector<char> &buffer)
{
	CTar32FileStatus &stat = pTarfile->m_currentfile_status;
	std::string fname2 = fname;

	EXTRACTINGINFOEX extractinfo;
	EXTRACTINGINFOEX64 exinfo64;
	MakeExtractingInfo(pTarfile,fname2.c_str(),extractinfo,exinfo64);
	{
		int ret = SendArcMessage(cmdinfo, ARCEXTRACT_BEGIN, &extractinfo,&exinfo64);
		if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);}
		fname2 = extractinfo.exinfo.szDestFileName;
	}

	//上書き確認
	if(cmdinfo.b_confirm_overwrite){
		switch(ConfirmOverwrite(cmdinfo, exinfo64)){
		case -1://cancel(abort)
			throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);
			break;
		case 1:	//yes to all
			cmdinfo.b_confirm_overwrite=false;
			break;
		}
	}

	size64 filesize = pTarfile->m_currentfile_status.original_size;

	CTar32InternalFile file; file.open(pTarfile);


	//std::ofstream fs_w;
	fast_fstream fs_w;
	if(!cmdinfo.b_print){
		mkdir_recursive(get_dirname(fname2.c_str()).c_str());
		fs_w.open(fname2.c_str(), std::ios::out|std::ios::binary);
		if(fs_w.fail()){return false;}
	}

	size64 readsize = 0;
	//static std::vector<char> buf;
	//const int bufsize=512*1024;
	//buf.resize(bufsize);
	const size_t bufsize=buffer.size();
	while(filesize ==-1 || readsize<filesize){
		size64 nextreadsize;
		if(filesize == -1){ // case ".gz",".Z",".bz2"
			//nextreadsize = sizeof(buf);
			nextreadsize=bufsize;
		}else{
			size64 nextreadsize64 = filesize-readsize;
			if(nextreadsize64 > bufsize){nextreadsize64 = bufsize;}
			nextreadsize = nextreadsize64;
			if(nextreadsize==0){
				Sleep(0);
			}
			// nextreadsize = (int)min(filesize-readsize, sizeof(buf));
		}
		if(nextreadsize==0){
			Sleep(0);
		}
		size64 n = file.read(&buffer[0],nextreadsize);
		readsize += n;
		if(cmdinfo.b_print){
			cmdinfo.output.write(&buffer[0],(size_t)n);	//TODO:size lost
		}else{
			fs_w.write(&buffer[0],n);
			if(fs_w.fail()){return false;}
		}
		if(n != nextreadsize){
			if(filesize == -1){ // case .gz/.Z/.bz2"
				break;
			}else{
				return false;
			}
		}
//		if(cmdinfo.hTar32StatusDialog){
			extractinfo.exinfo.dwWriteSize = (DWORD)readsize;
			exinfo64.exinfo.dwWriteSize = (DWORD)readsize;
			exinfo64.llWriteSize = readsize;
			int ret = SendArcMessage(cmdinfo, ARCEXTRACT_INPROCESS, &extractinfo,&exinfo64);
			if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);}
//		}
	}
	if(!cmdinfo.b_print){
		fs_w.close();
		struct _utimbuf ut;
		ut.actime = (stat.atime ? stat.atime : time(NULL));
		ut.modtime = (stat.mtime ? stat.mtime : time(NULL));
		int ret;
		ret = _utime(fname2.c_str(), &ut);
		ret = _chmod(fname2.c_str(), stat.mode);
	}
//	if(cmdinfo.hTar32StatusDialog){
		extractinfo.exinfo.dwWriteSize = (DWORD)readsize;
		exinfo64.exinfo.dwWriteSize = (DWORD)readsize;
		exinfo64.llWriteSize = readsize;
		int ret = SendArcMessage(cmdinfo, 6, &extractinfo,&exinfo64);
		if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);}
//	}
	return true;
}
Пример #25
0
unsigned long Read_VOD( char *theURL )
{ unsigned long N = 0;
  VODFiles *fp;
  FOFFSET jpgOffset, prev_Offset=0, prev_fpos, audioOffset;
  uint32_t VOBid;
  VOB_JPEG_Headers jH, prev_jH;
  VOB_Audio_Headers aH;
  int current_vmgi;
  int ok, nextFound;
  VMGIs vmgi;
  double tskipped = 0, audioDuration = 0;
  struct readtables {
	  int current_vmgi;
	  FOFFSET current_vmgiPos;
	  int VOB_Ns, vmgiAudioChunks, vmgiVideoFrames;
	  int frames;
	  int doubles;
  } *readtable, *rt;
  unsigned int readtableN = 0;
  char *mode = "rb";
  double frameRate;
  FILE *dumpFP = NULL;
  int pcloseDumpFP = 0, gotPipeSignal;
  size_t jpgFrameCount = 0, mp4FragCount = 0;
  char dirTemp[128] = "VODconverting-XXXXXX", *bURL = NULL;
  MPG4_Fragments mp4Frag;
  struct {
	  VOB_Dates StartDate;
	  VOB_Times StartTime;
	  int isSet;
#if defined(_MSC_VER) || defined(__MINGW32__)
	  struct _utimbuf ut;
#else
	  struct timeval t[2];
#endif
  } StartTimeStamp;
#if defined(_MSC_VER)
  POpenExProperties popProps;
#endif
#ifdef EXTRACTCHANNELVIEWS
  int ff;
  FILE *pfp[4] = {NULL, NULL, NULL, NULL};
#endif

	init_HRTime();
	HRTime_tic();
	if( (fp = open_VODFile( &FP, theURL, mode )) ){
		if( !validate_VODFile( fp, 0 ) ){
			fprintf( stderr, "Not a VOD file \"%s\"\n", theURL );
			close_VODFile(fp);
			return 0;
		}
		fprintf( stderr, "Opened VOD file \"%s\"\n", theURL );
#ifdef __APPLE_CC__
		fpBase = FP.theFile->_bf._base;
#endif
		readtable = (struct readtables*) calloc(1, sizeof(struct readtables));
		mkdtemp(dirTemp);
		bURL = strdup( basename(theURL) );
#if defined(WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
		strcat( dirTemp, "\\" );
#else
		strcat( dirTemp, "/" );
#endif
		fprintf( stderr, "@@\t average frequency: %gHz\n", (frameRate = VODFile_Find_averageRate(fp)) );
		CLEAR_MPG4_FRAGMENT(&mp4Frag);
		memset( &StartTimeStamp, 0, sizeof(StartTimeStamp) );
		VMGICHECK( Read_VMGI( fp ) ){
		  FOFFSET fpos;
			if( fp->hasMPG4 && !dumpFP ){
			   char command[1024];
#if defined(_MSC_VER) || defined(WIN32) || defined(__MINGW32__)
			   const char *mode = "wb";
#else
			   const char *mode = "w";
#endif
				snprintf( command, sizeof(command),
					    "ffmpeg -y -v 1 -i - -vcodec copy \"%s.%4d%02d%02d%02d%02d.mov\"",
						theURL,
						fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
						fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes );
	//			snprintf( command, sizeof(command), "cat > %s.fragments.mov -", theURL );
				fprintf( stderr, "Sending content to \"%s\"\n", command );
#if defined(_MSC_VER)
				popProps.commandShell = "ffmpeg.exe";
				popProps.shellCommandArg = NULL;
				popProps.runPriorityClass = ABOVE_NORMAL_PRIORITY_CLASS;
				popProps.finishPriorityClass = HIGH_PRIORITY_CLASS;
				dumpFP = popenEx( command, mode, &popProps );
#else
				dumpFP = popen( command, mode );
#endif
				if( dumpFP ){
					SetupPipeSignalHandler(&gotPipeSignal);
					pcloseDumpFP = 1;
				}
#ifdef EXTRACTCHANNELVIEWS
				snprintf( command, sizeof(command),
					    "ffmpeg -y -v 1 -i - -vf crop=360:288:0:0 -b:v 500k -vcodec mjpeg \"%s.%4d%02d%02d%02d%02d-camera1.mov\"",
						theURL,
						fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
						fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes );
#ifdef _MSC_VER
				pfp[0] = popenEx( command, mode, &popProps );
#else
				pfp[0] = popen( command, mode );
#endif
				snprintf( command, sizeof(command),
					    "ffmpeg -y -v 1 -i - -vf crop=360:288:360:0 -b:v 500k -vcodec mjpeg \"%s.%4d%02d%02d%02d%02d-camera2.mov\"",
						theURL,
						fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
						fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes );
#ifdef _MSC_VER
				pfp[1] = popenEx( command, mode, &popProps );
#else
				pfp[1] = popen( command, mode );
#endif
				snprintf( command, sizeof(command),
					    "ffmpeg -y -v 1 -i - -vf crop=360:288:0:288 -b:v 500k -vcodec mjpeg \"%s.%4d%02d%02d%02d%02d-camera3.mov\"",
						theURL,
						fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
						fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes );
#ifdef _MSC_VER
				pfp[2] = popenEx( command, mode, &popProps );
#else
				pfp[2] = popen( command, mode );
#endif
				snprintf( command, sizeof(command),
					    "ffmpeg -y -v 1 -i - -vf crop=360:288:360:288 -b:v 500k -vcodec mjpeg \"%s.%4d%02d%02d%02d%02d-camera4.mov\"",
						theURL,
						fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
						fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes );
#ifdef _MSC_VER
				pfp[3] = popenEx( command, mode, &popProps );
#else
				pfp[3] = popen( command, mode );
#endif
#endif // EXTRACTCHANNELVIEWS
			}
			current_vmgi = fp->current_vmgi;
			if( !StartTimeStamp.isSet ){
				StartTimeStamp.StartDate = fp->vmgi.StartDate;
				StartTimeStamp.StartTime = fp->vmgi.StartTime;
				StartTimeStamp.isSet = 1;
#ifdef _MSC_VER
				{ struct tm tmm = {0};
					// Fill out the modified time structure
					// tm_hour is supposed to be in UTC, so we correct for the fact we're in Western continental Europe
					tmm.tm_hour = fp->vmgi.StartTime.hours - 1;
					// guess whether DST was in effect:
					tmm.tm_isdst = (fp->vmgi.StartDate.month > 3 && fp->vmgi.StartDate.month < 11)? 1 : 0;
					tmm.tm_min = fp->vmgi.StartTime.minutes;
					tmm.tm_sec = fp->vmgi.StartTime.seconds;
					tmm.tm_mday = fp->vmgi.StartDate.day;
					// tm_mon is 0 based
					tmm.tm_mon = fp->vmgi.StartDate.month - 1;
					// tm_year starts at 1900
					tmm.tm_year = fp->vmgi.StartDate.year - 1900;
					
					// Convert tm to time_t
					StartTimeStamp.ut.actime = StartTimeStamp.ut.modtime = mktime(&tmm);
				}
#endif
			}
			fprintf( stderr, "## VMGI #%d @ 0x%lx (%.3g%%), %d video, %u audio frames%s%s, %4d%02d%02d::%02d:%02d:%02d - %4d%02d%02d::%02d:%02d:%02d\n",
				fp->current_vmgi, (unsigned long) fp->current_vmgiPos,
				((double)fp->current_vmgiPos)/((double) fp->fileSize) * 100.0,
				fp->vmgiVideoFrames, fp->vmgiAudioChunks,
				(fp->vmgi.VOB_Ns != fp->vmgiVideoFrames+fp->vmgiAudioChunks)? " plus something else" : "",
				(fp->vmgi.InfoType==2)? ", GPS" : "",
				fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
				fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes, fp->vmgi.StartTime.seconds,
				fp->vmgi.EndDate.year, fp->vmgi.EndDate.month, fp->vmgi.EndDate.day,
				fp->vmgi.EndTime.hours, fp->vmgi.EndTime.minutes, fp->vmgi.EndTime.seconds
			);
			fflush( stderr );
			if( N == 0 ){
				fpos = FFTELL(fp->theFile);
				// we save fp->vmgi because Read_VOB_JPEG_Header_Scan_Next() can update this field to the file's next VMGI
				// when in fact we still want to print out information from the current one...
				vmgi = fp->vmgi;
			}
#ifdef USE_VMGI
			readtableN += 1;
			if( (readtable = (struct readtables*) realloc( readtable, readtableN*sizeof(struct readtables) )) ){
				rt = &readtable[readtableN-1];
				rt->current_vmgi = current_vmgi;
				rt->current_vmgiPos = fp->vmgiPos[current_vmgi];
				rt->VOB_Ns = fp->vmgi.VOB_Ns;
				rt->vmgiAudioChunks = fp->vmgiAudioChunks;
				rt->vmgiVideoFrames = fp->vmgiVideoFrames;
				rt->frames = rt->doubles = 0;
			}
			else{
				rt = NULL;
			}
			// fp and fp->vmgi are always up to date and never ahead of us.
			vmgi = fp->vmgi;
			fpos = FFTELL(fp->theFile);
			fp->readContent = 1;
			for( VOBid = 0; VOBid_Check(fp, VOBid, NULL); VOBid++ ){
				fflush(stdout);
				switch( VODFILE_VOB_TYPE(fp,VOBid) ){
					case VMGI_VOB_TYPE_VIDEO:
						if( (ok = Read_VOB_xPEG_Header( fp, VOBid, &jH, &jpgOffset, &nextFound, &mp4Frag, DUMP_JPGS /*&& (fp->vmgi.InfoType==2)*/ )) ){
							if( ok < 0  ){
								fputs( "((", stderr );
							}
							if( VOB_Header_isJPEG( (VOB_Headers_Common*)&jH ) ){
							  size_t nameLen = (strlen(theURL)+strlen(dirTemp)+34)*sizeof(char);
							  char *tmpName = (char*) malloc(nameLen);
								if( tmpName ){
									snprintf( tmpName, nameLen, "%s%s.%04ld.jpg", dirTemp, bURL, fp->decodedFrames );
									if( dumpFP ){
										fclose(dumpFP);
									}
									if( (dumpFP = fopen(tmpName, "wb")) ){
										fwrite( fp->lastReadContent, sizeof(unsigned char),
											  fp->lastReadContentByteLength, dumpFP );
										fclose(dumpFP); dumpFP = NULL;
										jpgFrameCount += 1;
									}
									free(tmpName);
								}
								if( VOBid == 0 || VOBid == fp->vmgi.VOB_Ns - 1 ){
									fprintf( stderr, "jpeg image #%d at offset %ld; %hux%hu, %4d%02d%02d::%02d:%02d:%02d flags=%s\n",
										VOBid, (long) jpgOffset,
										jH.Width, jH.Height,
										jH.Date.year, jH.Date.month, jH.Date.day,
										jH.Time.hours, jH.Time.minutes, jH.Time.seconds,
										VOB_JPEG_Flags(&jH)
									);
									if( VOBid == 0 ){
										fputs( "...\n", stderr );
									}
								}
							}
							else if( VOB_Header_isMPG4( (VOB_Headers_Common*)&jH ) ){
								if( !dumpFP ){
								  size_t nameLen = (strlen(theURL)+strlen(dirTemp)+34)*sizeof(char);
								  char *tmpName = (char*) malloc(nameLen);
									if( tmpName ){
										snprintf( tmpName, nameLen, "%s%s.fragments.mp4", dirTemp, bURL, fp->decodedFrames );
										dumpFP = fopen(tmpName, "wb");
										free(tmpName);
									}
								}
								if( dumpFP ){
									fwrite( fp->lastReadContent, sizeof(unsigned char),
										  fp->lastReadContentByteLength, dumpFP );
									if( gotPipeSignal ){
#ifdef _MSC_VER
										pcloseEx(dumpFP);
#else
										pclose(dumpFP);
#endif
										dumpFP = NULL;
										goto done;
									}
									mp4FragCount += 1;
								}
#ifdef EXTRACTCHANNELVIEWS
								for( ff = 0 ; ff < 4 ; ff++ ){
									if( pfp[ff] ){
										fwrite( fp->lastReadContent, sizeof(unsigned char),
											  fp->lastReadContentByteLength, pfp[ff] );
										if( gotPipeSignal ){
#ifdef _MSC_VER
											pcloseEx(pfp[ff]);
#else
											pclose(pfp[ff]);
#endif
											pfp[ff] = NULL;
											goto done;
										}
									}
								}
#endif
#ifndef NO_FFMPEGLIBS_DEPEND
								fprintf( stderr, "MPEG4 fragment #%d.%d at offset %ld(%ld), %d(%lu) bytes of %lu; %hux%hu, %4d%02d%02d::%02d:%02d:%02d flags=%s\n",
									VOBid, mp4Frag.current.frameNr,
									(long) jpgOffset, (long) jpgOffset - (long) mp4Frag.fileOffset,
									mp4Frag.current.byteLength, jH.Length - sizeof(jH), mp4Frag.byteLength,
									jH.Width, jH.Height,
									jH.Date.year, jH.Date.month, jH.Date.day,
									jH.Time.hours, jH.Time.minutes, jH.Time.seconds,
									VOB_JPEG_Flags(&jH)
								);
#else
								fprintf( stderr, "MPEG4 fragment #%d.%d @0x%lx, %lu bytes; %hux%hu, %4d%02d%02d::%02d:%02d:%02d flags=%s\n",
									VOBid, mp4Frag.current.frameNr,
									(long) jpgOffset, mp4Frag.byteLength,
									jH.Width, jH.Height,
									jH.Date.year, jH.Date.month, jH.Date.day,
									jH.Time.hours, jH.Time.minutes, jH.Time.seconds,
									VOB_JPEG_Flags(&jH)
								);
#endif
							}

							if( fp->hasGPS ){
								if( fp->gpsData.fieldsRead > 0 ){
									fprintf( stderr, "\tGPS NMEA Sentence %s[%d] ; speed=%g\n", 
										   fp->nmeaSentence, fp->gpsData.fieldsRead, fp->gpsData.speed
									);
								}
							}
							if( ok > 0 ){
								if( rt ){
									rt->frames += 1;
									if( jpgOffset == prev_Offset ){
										rt->doubles += 1;
									}
								}
								tskipped += print_positions( stdout, fp, &vmgi, N, &jH, &prev_jH, jpgOffset, &prev_Offset, &fpos, &prev_fpos );
								N += 1;
							}
						};
						break;
					case VMGI_VOB_TYPE_AUDIO:
						Find_Next_VOB_Audio_Header(fp, NULL, NULL, 1);
						fp->curPos += 1;
						break;
					default:
						break;
				}
				fflush(stderr);
			}
			fp->readContent = 0;
			if( strncmp( fp->vmgi.Id, "VOBX", 4 ) == 0 && fp->vmgi.VOB_Ns == 0 ){
				fprintf( stderr, "Encountered an empty VOBX instead of a VOBS - assuming end of recording!\n" );
				break;
			}
#else	// !USE_VMGI
			fp->readContent = 1;
			while( (ok = Read_VOB_xPEG_Header_Scan_Next( fp, &jH, &jpgOffset, &nextFound, &mp4Frag, DUMP_JPGS )) || nextFound ){
				if( current_vmgi != fp->current_vmgi || readtableN == 0 ){
					current_vmgi = fp->current_vmgi;
					readtableN += 1;
					fprintf( stderr, "## VMGI #%d @ 0x%lx (%.3g%%), %d video, %u audio frames%s%s, %4d%02d%02d::%02d:%02d:%02d - %4d%02d%02d::%02d:%02d:%02d\n",
						fp->current_vmgi, (unsigned long) fp->current_vmgiPos,
						((double)fp->current_vmgiPos)/((double) fp->fileSize) * 100.0,
						fp->vmgiVideoFrames, fp->vmgiAudioChunks,
						(fp->vmgi.VOB_Ns != fp->vmgiVideoFrames+fp->vmgiAudioChunks)? " plus something else" : "",
						(fp->vmgi.InfoType==2)? ", GPS" : "",
						fp->vmgi.StartDate.year, fp->vmgi.StartDate.month, fp->vmgi.StartDate.day,
						fp->vmgi.StartTime.hours, fp->vmgi.StartTime.minutes, fp->vmgi.StartTime.seconds,
						fp->vmgi.EndDate.year, fp->vmgi.EndDate.month, fp->vmgi.EndDate.day,
						fp->vmgi.EndTime.hours, fp->vmgi.EndTime.minutes, fp->vmgi.EndTime.seconds
					);
					fflush( stderr );
					if( (readtable = (struct readtables*) realloc( readtable, readtableN*sizeof(struct readtables) )) ){
						rt = &readtable[readtableN-1];
						rt->current_vmgi = current_vmgi;
						rt->current_vmgiPos = fp->vmgiPos[current_vmgi];
						rt->VOB_Ns = fp->vmgi.VOB_Ns;
						rt->vmgiAudioChunks = fp->vmgiAudioChunks;
						rt->vmgiVideoFrames = fp->vmgiVideoFrames;
						rt->frames = rt->doubles = 0;
					}
					else{
						rt = NULL;
					}
				}
				if( ok ){
					fflush(stdout);
					if( ok < 0 ){
						fputs( "((", stderr );
					}
					if( VOB_Header_isJPEG( (VOB_Headers_Common*)&jH ) ){
					  size_t nameLen = (strlen(theURL)+strlen(dirTemp)+34)*sizeof(char);
					  char *tmpName = (char*) malloc(nameLen);
						if( tmpName ){
							snprintf( tmpName, nameLen, "%s%s.%04ld.jpg", dirTemp, bURL, fp->decodedFrames );
							if( dumpFP ){
								fclose(dumpFP);
							}
							if( (dumpFP = fopen(tmpName, "wb")) ){
								fwrite( fp->lastReadContent, sizeof(unsigned char),
									  fp->lastReadContentByteLength, dumpFP );
								fclose(dumpFP); dumpFP = NULL;
								jpgFrameCount += 1;
							}
							free(tmpName);
						}
						fprintf( stderr, "jpeg image #%d:%d at offset %lu; %hux%hu, %4d%02d%02d::%02d:%02d:%02d\n",
							fp->current_vmgi, fp->current_VOBDes, (unsigned long) jpgOffset,
							jH.Width, jH.Height,
							jH.Date.year, jH.Date.month, jH.Date.day,
							jH.Time.hours, jH.Time.minutes, jH.Time.seconds
						);
					}
					else if( VOB_Header_isMPG4( (VOB_Headers_Common*)&jH ) ){
						if( !dumpFP ){
						  size_t nameLen = (strlen(theURL)+strlen(dirTemp)+34)*sizeof(char);
						  char *tmpName = (char*) malloc(nameLen);
							if( tmpName ){
								snprintf( tmpName, nameLen, "%s%s.fragments.mp4", dirTemp, bURL, fp->decodedFrames );
								dumpFP = fopen(tmpName, "wb");
								free(tmpName);
							}
						}
						if( dumpFP ){
							fwrite( fp->lastReadContent, sizeof(unsigned char),
								  fp->lastReadContentByteLength, dumpFP );
							mp4FragCount += 1;
						}
						fprintf( stderr, "MPEG4 fragment #%d:%d at offset %lu, %lu bytes; %hux%hu, %4d%02d%02d::%02d:%02d:%02d\n",
							fp->current_vmgi, fp->current_VOBDes, (unsigned long) jpgOffset, fp->lastReadContentByteLength,
							jH.Width, jH.Height,
							jH.Date.year, jH.Date.month, jH.Date.day,
							jH.Time.hours, jH.Time.minutes, jH.Time.seconds
						);
					}
					fflush( stderr );
					if( ok > 0 ){
						if( rt ){
							rt->frames += 1;
							if( jpgOffset == prev_Offset ){
								rt->doubles += 1;
							}
						}
						tskipped += print_positions( stdout, fp, &vmgi, N, &jH, &prev_jH, jpgOffset, &prev_Offset, &fpos, &prev_fpos );
						N += 1;
					}
				}
			}
			fp->readContent = 0;
#endif	// USE_VMGI
		}
done:
		// whether or not the scan of the file is complete is up to us to decide, though the routines in brigade.c
		// will set the flag if they encounter EOF.
		fp->scanComplete = 1;
		if( dumpFP ){
		  char fname[1024];
			if( pcloseDumpFP ){
				fflush(stdout);
				fprintf( stderr, "Waiting for ffmpeg to terminate..." ); fflush(stderr);
#ifdef _MSC_VER
				pcloseEx(dumpFP);
				fprintf( stderr, " took %g user and %g kernel seconds\n",
					   popProps.times.user, popProps.times.kernel );
#else
				pclose(dumpFP);
				fputs( "\n", stderr );
#endif
				snprintf( fname, sizeof(fname), "%s.%4d%02d%02d%02d%02d.mov",
					    theURL, StartTimeStamp.StartDate.year, StartTimeStamp.StartDate.month, StartTimeStamp.StartDate.day,
					    StartTimeStamp.StartTime.hours, StartTimeStamp.StartTime.minutes );
#ifdef _MSC_VER
				_utime( fname, &StartTimeStamp.ut );
#endif
			}
			else{
				fclose(dumpFP);
			}
			dumpFP = NULL;
		}
#ifdef EXTRACTCHANNELVIEWS
		for( ff = 0 ; ff < 4 ; ff++ ){
			if( pfp[ff] ){
#ifdef _MSC_VER
				pcloseEx(pfp[ff]);
#else
				pclose(pfp[ff]);
#endif
				pfp[ff] = NULL;
			}
		}
#endif
		if(0){
		  int aN = 0, pN = fp->NaudioPos;
		  extern int Find_All_VOB_Audio_Headers( VODFiles *fp );
			fprintf( stderr, "Doing an exhaustive scan for audio ... " );
			fflush(stderr);
			aN = Find_All_VOB_Audio_Headers(fp);
			if( aN != pN ){
				fprintf( stderr, " encountered %d chunks", aN );
			}
			fputs( "\n", stderr );
			rewind_VODFile(fp, NULL);
		}
		else{
			rewind_VODFile(fp, NULL);
		}
		if( fp ){
			fprintf( stderr, "Read %d VMGIs and encountered %d audio chunks while scanning for video frames\n",
				    fp->NvmgiPos, fp->NaudioPos
			);
		}
		else{
			fprintf( stderr, "Error reopening file after rewind (%s)\n", strerror(errno) );
		}
		if( fp && fp->NaudioPos ){
		  FILE *audioFP = NULL;
		  char *tmpName;
		  int tnl;
			if( (tmpName = (char*) malloc( (tnl = strlen(theURL)+32) * sizeof(char) )) ){
				snprintf( tmpName, tnl, "%s.au1", fp->theURL );
				audioFP = fopen( tmpName, "wb" );
				free(tmpName), tmpName = NULL;
			}
			for( VOBid = 0, audioDuration = 0 ; VOBid < fp->NaudioPos ; VOBid++ ){
			  uint32_t audioLength;
			  double duration, freq[] = { 8, 11025, 22050, 44100 };
				if( VOBid == 0 || fp->audioPos[VOBid] != fp->audioPos[VOBid-1] ){
					Read_VOB_Audio_Header_From_audioPos( fp, VOBid, &aH, &audioOffset, &audioLength, 1, audioFP );
					if( aH.Audio_Channel == 2 ){
						duration = audioLength / 2 / freq[aH.Audio_Rate];
					}
					else{
						duration = audioLength / freq[aH.Audio_Rate];
					}
					fprintf( stderr, "Audio chunk #%d: %lu bytes at 0x%lx; duration=%gs\n",
						    VOBid, audioLength, (unsigned long) audioOffset, duration
					);
					audioDuration += duration;
				}
			}
			if( audioFP ){
				fclose(audioFP);
			}
		}
		if( audioDuration ) {
			fprintf( stderr, "Total audio duration: %gs\n", audioDuration );
		}
		Finalise_MPG4_Fragment(&mp4Frag);
		close_VODFile(fp);
		fprintf( stderr, "Average skipped bytes per frame: %g\n", tskipped / N );
#ifdef DEBUG
		if( readtable ){
		  int i, AudioChunks = 0;
			for( i = 0; i< readtableN; i++){
				fprintf( stderr, "%03d VMGI #%d@0x%lu\tframes=%d\tVOB_Ns=%d,VideoFrames=%d,AudioChunks=%d",
					    i, readtable[i].current_vmgi, (unsigned long)readtable[i].current_vmgiPos,
					    readtable[i].frames, readtable[i].VOB_Ns, readtable[i].vmgiVideoFrames, readtable[i].vmgiAudioChunks
				);
				if( rt->doubles ){
					fprintf( stderr, "\tdoubles=%d", rt->doubles );
				}
				fputc( '\n', stderr );
				AudioChunks += readtable[i].vmgiAudioChunks;
			}
			free(readtable);
			readtable = NULL;
		}
#endif
		{ char command[1024];
			if( jpgFrameCount ){
				snprintf( command, sizeof(command),
					    "ffmpeg -y -r %g -i %s%s.%%04d.jpg -vcodec copy \"%s.%4d%02d%02d%02d%02d.mov\"",
					    frameRate, dirTemp, bURL,
					    theURL, StartTimeStamp.StartDate.year, StartTimeStamp.StartDate.month, StartTimeStamp.StartDate.day,
					    StartTimeStamp.StartTime.hours, StartTimeStamp.StartTime.minutes );
				system( command );
			}
//			if( mp4FragCount ){
//				snprintf( command, sizeof(command), "ffmpeg -y -i %s%s.fragments.mp4 -vcodec copy %s.converted.mov",
//					    dirTemp, bURL, theURL );
//				system( command );
//			}
#if defined(WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
			snprintf( command, sizeof(command), "rmdir /s /q %s", dirTemp );
#else
			snprintf( command, sizeof(command), "rm -rf %s", dirTemp );
#endif
			system(command);
			snprintf( command, sizeof(command), "%s.%4d%02d%02d%02d%02d.mov",
				    theURL, StartTimeStamp.StartDate.year, StartTimeStamp.StartDate.month, StartTimeStamp.StartDate.day,
				    StartTimeStamp.StartTime.hours, StartTimeStamp.StartTime.minutes );
#ifdef _MSC_VER
			_utime( command, &StartTimeStamp.ut );
#endif
			free(bURL);
		}
#ifdef USE_VMGI
		if( mp4Frag.valid ){
			fprintf( stderr, "Read %lu %gHz 1sec fragments from \"%s\" in %g sec (using VMGI info)\n",
				   N, frameRate, theURL, HRTime_toc() );
		}
		else{
			fprintf( stderr, "Read %lu frames from \"%s\" in %g sec (using VMGI info)\n", N, theURL, HRTime_toc() );
		}
#else
		fprintf( stderr, "Read %lu frames from \"%s\" in %g sec\n", N, theURL, HRTime_toc() );
#endif
	}
	else{
Пример #26
0
int main(int argc, char *argv[]) {
	int k, i, n, c;
	int firstarg=1;
	FILE *input, *output;
/*	char destination[FILENAME_MAX]; */
	char infilecivil[FILENAME_MAX], outfilecivil[FILENAME_MAX];
	time_t infiletime, outfiletime;
	char *s;
	time_t timenow;
/*	time_t targettime, sourcetime; */

/*	First lay in background of current date and time */
	timenow = time (NULL);
	if (timenow == -1) fprintf(stderr, "Time does not exist!\n");
	tm = localtime (&timenow);
	year = tm->tm_year + 1900;
	month = tm->tm_mon;
	day = tm->tm_mday;
	hour = tm->tm_hour;
	minute = tm->tm_min;
	second = tm->tm_sec;

	defyear = year;				/* remember current year */
	defmonth = month;			/* remember current month */
	defday = day;				/* remember current day */

/*	if (argc < firstarg + 2) { */
	if (argc < firstarg + 1) showusage (argc, argv);

	firstarg = commandline(argc, argv, firstarg);

/*	if (argc < firstarg + 2) { */
	if (argc < firstarg + 1) showusage(argc, argv);

/*	if (verboseflag != 0)  */
	if (verboseflag != 0 && (startchar != 0 || endchar != 255)) 
		printf("Start %d (%c) end %d (%c)\n", 
			startchar, startchar, endchar, endchar);

	if (strcmp(destination, "") == 0) {	/* last arg is destination direct ? */
/*		strcpy(destination, argv[argc-1]); */
		destination = argv[argc-1];		/* the old way of doing this */
		argc--;
		printf("WARNING: destination not specified, using %s\n", destination);
	}

	if (verboseflag) printf("Destination is %s\n", destination);

/*	for (k = firstarg; k < argc-1; k++) { */
	for (k = firstarg; k < argc; k++) {

		strcpy(infilename, argv[k]);
		s = stripfilename(infilename);
		c = *s;										/* 1992/Oct/ 11 */
		if (c >= 'a' && c <= 'z') c = c  + 'A' - 'a';
		if (c < startchar || c > endchar) continue;

		strcpy(outfilename, destination);
		strcat(outfilename, "\\");
		strcat(outfilename, s);
	
		if (getinfo(infilename, 0) < 0) continue;
/*		infiletime = statbuf.st_atime; */
		infiletime = statbuf[0].st_atime;
		strcpy(infilecivil, timeptr);

		if (traceflag != 0) printf("Considering file %s\n", infilename);

		if (thresholdflag) {
			if (infiletime < newtime){
				if (verboseflag)
					printf("%s not younger than threshold\n", infilename);
				continue;
			}
		}

		if (getinfo(outfilename, 1) < 0) {
			outfiletime = 0;
			strcpy(outfilecivil, "");			
		} 
		else {
/*			outfiletime = statbuf.st_atime; */
			outfiletime = statbuf[1].st_atime;
			strcpy(outfilecivil, timeptr);
		}

/*		if (outfiletime == 0 || outfiletime < infiletime) { */
		if (outfiletime != 0 && outfiletime >= infiletime) {
			if (traceflag) printf("Not younger than destination\n");
			continue;
		}
		
/*		printf("Copying %s ", infilename); */
		printf("Copying %s ", s);
/*		if (strcmp(outfilecivil, "") != 0) { */
		n = strlen(s);
		for (i = n; i < 14; i++) putc(' ', stdout);
		printf("new: %s   ", infilecivil);
		if (strcmp(outfilecivil, "") != 0) 
			printf("old: %s", outfilecivil);
/*		} */
		printf("\n");
		if ((input = fopen(infilename, "rb")) == NULL) {
			perror(infilename);
			continue;
		}
		if (outputflag == 0) {
			printf("Skipping %s\n", outfilename);
			fclose(input);
			continue;
		}
		if (safeflag != 0) { /* temporary, until debugged */
			if ((output = fopen(outfilename, "rb")) != NULL) {
				fclose(output);
				printf("%s already exist\n", outfilename);
				fclose(input);
				continue;
			}
		}
		if ((output = fopen(outfilename, "wb")) == NULL) {
			fclose(input);
			perror(outfilename);
			exit(3);
		}
/*		while ((c = getc(input)) != EOF) putc(c, output); */
		copyfile(output, input);
		if (ferror(input) != 0) {
			perror(infilename);
		}
		fclose(input);
		if (ferror(output) != 0) {
			perror(outfilename);
			exit(5);
		}
		fclose(output);
		if (copydate != 0) {
			timebuf.actime = statbuf[0].st_atime; 
			timebuf.modtime = statbuf[0].st_atime; 
/*			if (utime(argv[k], &timebuf) != 0) {  */
/*			if (utime(outfilename, &timebuf) != 0) {  */
			if (_utime(outfilename, &timebuf) != 0) { 
				fprintf(stderr, "Unable to modify date/time\n");
				perror(argv[1]);
				exit(3);
			} 
		}
/*		} */

/*		if (traceflag != 0) {
			if (getinfo(argv[1]) < 0) exit(1);
		} */
	}
	return 0;
}
Пример #27
0
//从包中解出全部文件
bool KPackFileManager::UnpackAll(int nPakIndex, int& nUnpackCount, const char* pDestPath, const char* pFileNamePrefix)
{
	nUnpackCount = 0;
	if (pFileNamePrefix == NULL)
		pFileNamePrefix = "";

	if (nPakIndex < 0 || nPakIndex >= PACK_FILE_SHELL_MAX_SUPPORT_PAK_NUM || !m_PackItemList[nPakIndex].pIOFile ||
		pDestPath == NULL || pDestPath[0] == 0)
	{
		return false;
	}
	int		nFileNameStartOffset = strlen(pDestPath);
	if (nFileNameStartOffset + 128 > MAX_PATH)
		return false;

	g_CreatePath(pDestPath);
	char	szFullName[MAX_PATH] = "";
	char*	pElemName = NULL;
	strcpy(szFullName, pDestPath);
	if (szFullName[nFileNameStartOffset - 1] == '\\')		/// 文件名都是带有'\\'的,eg:\image\effect\sfx\关卡\地狱鬼手.3e
	{
		pElemName = szFullName + nFileNameStartOffset - 1;
	}
	else
	{
		pElemName = szFullName + nFileNameStartOffset;
	}

	ELEM_FILE_INFO	info;
	info.nPakIndex = nPakIndex;
	PACK_ITEM& item = m_PackItemList[nPakIndex];

	for (info.nElemIndex = 0; info.nElemIndex < (int)item.Header.uCount; info.nElemIndex++)
	{
		XPackIndexInfo& IndexInfo = item.pIndexList[info.nElemIndex];
		info.uId = IndexInfo.uId;
	
		KPackFilePartner::PACKPARTNER_ELEM_INFO	PartnerInfo;
		if (m_PackPartnerList[info.nPakIndex].GetElemInfo(info.uId, PartnerInfo))
		{
			if (pFileNamePrefix[0])
			{
				if (strstr(PartnerInfo.szFileName, pFileNamePrefix) != PartnerInfo.szFileName)
					continue;	//排除前缀不符合的文件
			}
			strcpy(info.szFileName, PartnerInfo.szFileName);
			info.uCRC = PartnerInfo.uCRC;
			info.uTime = PartnerInfo.uTime;
		}
		else
		{
			if (pFileNamePrefix[0])
				continue;
			sprintf(info.szFileName, "\\_-ID-_%08x", info.uId);		///这边没看懂(以ID作为名字)
			info.uCRC = 0;
			info.uTime = 0;
		}
//		info.uCompressFlag = (IndexInfo.uCompressSizeFlag & (~XPACK_COMPRESS_SIZE_FILTER));
//		info.uSize = IndexInfo.uSize;
//		info.uStoreSize = (IndexInfo.uCompressSizeFlag & XPACK_COMPRESS_SIZE_FILTER);

		strcpy(pElemName, info.szFileName);				/// 路径 + 文件名
		char* pLastSplit = strrchr(pElemName, '\\');	/// 查找字符在指定字符串中从后面开始的第一次出现的位置  <---> strchr
		if (pLastSplit && pLastSplit != pElemName)		/// 对文件夹的处理?:文件名可以是带有目录的形式,eg: \image\dc\B2_M7_1.Mtl
		{
			*pLastSplit = 0;
			g_CreatePath(szFullName);			
			*pLastSplit = '\\';
		}
		//----解开存盘----
		UnpackElemByIndex(nPakIndex, info.nElemIndex, szFullName);

		//----修改文件时间----
		if (info.uTime)
		{
			_utimbuf time;
			time.actime = time.modtime = info.uTime;
			_utime(szFullName, &time);
		}

		nUnpackCount++;
	}
	return true;
}
Пример #28
0
int main(int argc, char *argv[]) {
	char infilename[FILENAME_MAX], outfilename[FILENAME_MAX], bakfilename[FILENAME_MAX];
	FILE *input, *output;
	int m, firstarg = 1;
	int backflag;		/* whether had to rename in file */
	char *s;

	if (argc < firstarg + 1) showusage(argc, argv);
	
/*	while (*argv[firstarg] == '-') */
	while (firstarg < argc && *argv[firstarg] == '-') {
		if (strchr(argv[firstarg], '?') != NULL) showusage(argc, argv);
		if (strchr(argv[firstarg], 'v') != NULL) verboseflag = 1;
		if (strchr(argv[firstarg], 't') != NULL) traceflag = 1;
		if (strchr(argv[firstarg], 'l') != NULL) linestrip = 1;
		if (strchr(argv[firstarg], 'i') != NULL) inlineflag = 1;
		if (strchr(argv[firstarg], 'p') != NULL) commentflag = 1;
		if (strchr(argv[firstarg], 'r') != NULL) stripcontrolm = 1;
		if (strchr(argv[firstarg], 'c') != NULL) checkcontrol = 1;
		if (strchr(argv[firstarg], 'f') != NULL) deleteback = 1;
		if (strchr(argv[firstarg], 'd') != NULL) {
			firstarg++;
			destination = argv[firstarg];
		}
		firstarg++;
	}

	for (m = firstarg; m < argc; m++) {
		backflag=0; linestripped=0; inlinestrip=0;
		strcpy(infilename, argv[m]);
		if (strcmp(destination, "") != 0) {
			strcpy(outfilename, destination);
			strcat(outfilename, "\\");
			strcat(outfilename, stripname(argv[m]));
		}
		else strcpy(outfilename, stripname(argv[m]));
		if (strcmp(infilename, outfilename) == 0) {
			strcpy (bakfilename, infilename);
			if ((s = strrchr(infilename, '.')) != NULL) {
				strcpy (s, ".bak");
				remove (infilename);
				rename (bakfilename, infilename);
				backflag++;
			}
		}
		if (traceflag != 0) printf("Opening %s and %s\n", 
			infilename,	outfilename);
		if ((input = fopen(infilename, "r")) == NULL) {
			perror(infilename); exit(1);
		}
		if (stripcontrolm != 0) {
			if ((output = fopen(outfilename, "wb")) == NULL) {
				perror(outfilename); exit(1);
			}
		}
		else {
			if ((output = fopen(outfilename, "w")) == NULL) {
				perror(outfilename); exit(1);
			}
		}
		if (traceflag != 0) printf("Stripping %s\n", infilename);
		while (fgets(buffer, MAXLINE, input) != NULL) {
			if (stripcomments (buffer) == 0) {
				if (checkcontrol != 0) scancontrol(buffer);
				if (fputs(buffer, output) == EOF) {
					perror(outfilename); break;
				}
			}
		}

		if (traceflag != 0) printf("Closing %s and %s\n", 
			infilename, outfilename);
		fclose(input);
		if (ferror(output) != 0) {
			perror(outfilename); exit(1);
		}
		else fclose(output);

		if (verboseflag != 0) {
			if (linestripped > 0 || inlinestrip > 0) {
				printf("Stripped ");
				if (linestripped > 0) 
					printf("%d complete lines ", linestripped);
				if (inlinestrip > 0) 
					printf("%d comments in lines ", inlinestrip); 
				putc('\n', stdout);
			}				
		}
		if (traceflag != 0) printf("Copying date and time\n");
		if (getinfo(infilename, verboseflag) < 0) {
			exit(1);
		}
	
		timebuf.actime = statbuf.st_atime;
		timebuf.modtime = statbuf.st_atime;
		if (_utime(outfilename, &timebuf) != 0) {
			fprintf(stderr, "Unable to modify date/time\n");
			perror(outfilename);
/*			exit(3); */
		}

/*		see if it worked */
		if (getinfo(outfilename, traceflag) < 0) exit(1);
		
		if (backflag != 0 && deleteback != 0)
			remove(infilename);
	}
	return 0;
}