Exemple #1
0
//void possect_add_old(u32 key, const Pvoid_t tokens);
void possect_add(const Pvoid_t tokens)
{
        static char *posbuf;
        static char *xidbuf;
                
        if (!posbuf){
                posbuf = xmalloc(iblock_size * 8 + 8);
                memset(posbuf, 0, iblock_size * 8 + 8);
                xidbuf = xmalloc((iblock_size * 2 + 3) * 8);
                memset(xidbuf, 0, (iblock_size * 2 + 3) * 8);
        }

        Word_t *ptr;
        u32 len, xoffs, poffs, prev_offs, prev_xid, 
                xsum, xmax, osum, omax;
        Word_t xid = poffs = prev_offs = prev_xid =\
                xsum = osum = osum = omax = xmax = len = 0;
        
        JLF(ptr, tokens, xid);
        while (ptr){
                growing_glist *g = (growing_glist*)*ptr;
                *ptr = poffs;
                rice_encode(posbuf, &poffs, g->lst.lst, g->lst.len);
                free(g);

                xsum += xid - prev_xid;
                osum += poffs - prev_offs;
                
                if (xid - prev_xid > xmax)
                        xmax = xid - prev_xid;
                if (poffs - prev_offs > omax)
                        omax = poffs - prev_offs;

                prev_xid = xid;
                prev_offs = poffs;

                ++len;
                JLN(ptr, tokens, xid);
        }
        poffs = BITS_TO_BYTES(poffs);
        
        xid = prev_xid = prev_offs = xoffs = 0;

        elias_gamma_write(xidbuf, &xoffs, len + 1);

        if (!len)
                goto write_buffers;

        u32 rice_f1 = estimate_rice_f_param(xsum, xmax, len);
        u32 rice_f2 = estimate_rice_f_param(osum, omax, len);
       
        rice_write(xidbuf, &xoffs, rice_f1, 2);
        rice_write(xidbuf, &xoffs, rice_f2, 2);

        JLF(ptr, tokens, xid);
        while (ptr){
                rice_write(xidbuf, &xoffs, xid - prev_xid, rice_f1);
                prev_xid = xid;
                rice_write(xidbuf, &xoffs, *ptr - prev_offs, rice_f2);
                prev_offs = *ptr;
                JLN(ptr, tokens, xid);
        }

write_buffers:
        xoffs = BITS_TO_BYTES(xoffs);
        
        toc_e toc;
        toc.offs = ftello64(data_f);
        toc.val = xoffs;
        fwrite(&toc, sizeof(toc_e), 1, toc_f);
        
        fwrite(xidbuf, xoffs, 1, data_f);
        fwrite(posbuf, poffs, 1, data_f);
        memset(xidbuf, 0, xoffs);
        memset(posbuf, 0, poffs);
}
Exemple #2
0
/* casted tell */
long long unsigned int xtell(FILE *f)
{
    return (long long unsigned int) ftello64(f);
}
Exemple #3
0
	int64_t fileTell( FILE * p_file )
	{
		return ftello64( p_file );
	}
Exemple #4
0
static int
do_test (void)
{
  size_t size;
  char *buf;
  FILE *fp = open_memstream (&buf, &size);
  if (fp == NULL)
    {
      puts ("open_memstream failed");
      return 1;
    }

  off64_t off = ftello64 (fp);
  if (off != 0)
    {
      puts ("initial position wrong");
      return 1;
    }

  if (fseek (fp, 32768, SEEK_SET) != 0)
    {
      puts ("fseek failed");
      return 1;
    }

  if (fputs ("foo", fp) == EOF)
    {
      puts ("fputs failed");
      return 1;
    }

  if (fclose (fp) == EOF)
    {
      puts ("fclose failed");
      return 1;
    }

  if (size != 32768 + 3)
    {
      printf ("expected size %d, got %zu\n", 32768 + 3, size);
      return 1;
    }

  for (int i = 0; i < 32768; ++i)
    if (buf[i] != '\0')
      {
	printf ("byte at offset %d is %#hhx\n", i, buf[i]);
	return 1;
      }

  if (memcmp (buf + 32768, "foo", 3) != 0)
    {
      puts ("written string incorrect");
      return 1;
    }

  /* Mark the buffer.  */
  memset (buf, 'A', size);
  free (buf);

  /* Try again, this time with write mode enabled before the seek.  */
  fp = open_memstream (&buf, &size);
  if (fp == NULL)
    {
      puts ("2nd open_memstream failed");
      return 1;
    }

  off = ftello64 (fp);
  if (off != 0)
    {
      puts ("2nd initial position wrong");
      return 1;
    }

  if (fputs ("bar", fp) == EOF)
    {
      puts ("2nd fputs failed");
      return 1;
    }

  if (fseek (fp, 32768, SEEK_SET) != 0)
    {
      puts ("2nd fseek failed");
      return 1;
    }

  if (fputs ("foo", fp) == EOF)
    {
      puts ("3rd fputs failed");
      return 1;
    }

  if (fclose (fp) == EOF)
    {
      puts ("2nd fclose failed");
      return 1;
    }

  if (size != 32768 + 3)
    {
      printf ("2nd expected size %d, got %zu\n", 32768 + 3, size);
      return 1;
    }

  if (memcmp (buf, "bar", 3) != 0)
    {
      puts ("initial string incorrect in 2nd try");
      return 1;
    }

  for (int i = 3; i < 32768; ++i)
    if (buf[i] != '\0')
      {
	printf ("byte at offset %d is %#hhx in 2nd try\n", i, buf[i]);
	return 1;
      }

  if (memcmp (buf + 32768, "foo", 3) != 0)
    {
      puts ("written string incorrect in 2nd try");
      return 1;
    }

  return 0;
}
Exemple #5
0
/*enumerate directories*/
GF_EXPORT
GF_Err gf_enum_directory(const char *dir, Bool enum_directory, gf_enum_dir_item enum_dir_fct, void *cbck, const char *filter)
{
#ifdef WIN32
	wchar_t item_path[GF_MAX_PATH];
#else
	char item_path[GF_MAX_PATH];
#endif
	GF_FileEnumInfo file_info;

#if defined(_WIN32_WCE)
	char _path[GF_MAX_PATH];
	unsigned short path[GF_MAX_PATH];
	unsigned short w_filter[GF_MAX_PATH];
	char file[GF_MAX_PATH];
#elif defined(WIN32)
	wchar_t path[GF_MAX_PATH], *file;
	wchar_t w_filter[GF_MAX_PATH];
	wchar_t w_dir[GF_MAX_PATH];
	char *mbs_file, *mbs_item_path;
#else
	char path[GF_MAX_PATH], *file;
#endif

#ifdef WIN32
	WIN32_FIND_DATAW FindData;
	HANDLE SearchH;
#else
	DIR *the_dir;
	struct dirent* the_file;
	struct stat st;
#endif

	if (!dir || !enum_dir_fct) return GF_BAD_PARAM;

	if (filter && (!strcmp(filter, "*") || !filter[0])) filter=NULL;

	memset(&file_info, 0, sizeof(GF_FileEnumInfo) );

	if (!strcmp(dir, "/")) {
#if defined(WIN32) && !defined(_WIN32_WCE)
		u32 len;
		char *drives, *volume;
		len = GetLogicalDriveStrings(0, NULL);
		drives = (char*)gf_malloc(sizeof(char)*(len+1));
		drives[0]=0;
		GetLogicalDriveStrings(len, drives);
		len = (u32) strlen(drives);
		volume = drives;
		file_info.directory = GF_TRUE;
		file_info.drive = GF_TRUE;
		while (len) {
			enum_dir_fct(cbck, volume, "", &file_info);
			volume += len+1;
			len = (u32) strlen(volume);
		}
		gf_free(drives);
		return GF_OK;
#elif defined(__SYMBIAN32__)
		RFs iFs;
		TDriveList aList;
		iFs.Connect();
		iFs.DriveList(aList);
		for (TInt i=0; i<KMaxDrives; i++) {
			if (aList[i]) {
				char szDrive[10];
				TChar aDrive;
				iFs.DriveToChar(i, aDrive);
				sprintf(szDrive, "%c:", (TUint)aDrive);
				enum_dir_fct(cbck, szDrive, "", &file_info);
			}
		}
		iFs.Close();
		FlushItemList();
		return GF_OK;
#endif
	}


#if defined (_WIN32_WCE)
	switch (dir[strlen(dir) - 1]) {
	case '/':
	case '\\':
		sprintf(_path, "%s*", dir);
		break;
	default:
		sprintf(_path, "%s%c*", dir, GF_PATH_SEPARATOR);
		break;
	}
	CE_CharToWide(_path, path);
	CE_CharToWide((char *)filter, w_filter);
#elif defined(WIN32)
	{
		const char* tmpdir = dir;
		gf_utf8_mbstowcs(w_dir, sizeof(w_dir), &tmpdir);
	}
	switch (w_dir[wcslen(w_dir) - 1]) {
	case '/':
	case '\\':
		swprintf(path, MAX_PATH, L"%s*", w_dir);
		break;
	default:
		swprintf(path, MAX_PATH, L"%s%c*", w_dir, GF_PATH_SEPARATOR);
		break;
	}
	{
		const char* tmpfilter = filter;
		gf_utf8_mbstowcs(w_filter, sizeof(w_filter), &tmpfilter);
	}
#else
	strcpy(path, dir);
	if (path[strlen(path)-1] != '/') strcat(path, "/");
#endif

#ifdef WIN32
	SearchH= FindFirstFileW(path, &FindData);
	if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR;

#if defined (_WIN32_WCE)
	_path[strlen(_path)-1] = 0;
#else
	path[wcslen(path)-1] = 0;
#endif

	while (SearchH != INVALID_HANDLE_VALUE) {

#else

	the_dir = opendir(path);
	if (the_dir == NULL) {
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot open directory %s for enumeration: %d\n", path, errno));
		return GF_IO_ERR;
	}
	the_file = readdir(the_dir);
	while (the_file) {

#endif

		memset(&file_info, 0, sizeof(GF_FileEnumInfo) );


#if defined (_WIN32_WCE)
		if (!wcscmp(FindData.cFileName, _T(".") )) goto next;
		if (!wcscmp(FindData.cFileName, _T("..") )) goto next;
#elif defined(WIN32)
		if (!wcscmp(FindData.cFileName, L".")) goto next;
		if (!wcscmp(FindData.cFileName, L"..")) goto next;
#else
		if (!strcmp(the_file->d_name, "..")) goto next;
		if (the_file->d_name[0] == '.') goto next;
#endif

#ifdef WIN32
		file_info.directory = (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? GF_TRUE : GF_FALSE;
		if (!enum_directory && file_info.directory) goto next;
		if (enum_directory && !file_info.directory) goto next;
#endif

		if (filter) {
#if defined (_WIN32_WCE)
			short ext[30];
			short *sep = wcsrchr(FindData.cFileName, (wchar_t) '.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#elif defined(WIN32)
			wchar_t ext[30];
			wchar_t *sep = wcsrchr(FindData.cFileName, L'.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#else
			char ext[30];
			char *sep = strrchr(the_file->d_name, '.');
			if (!sep) goto next;
			strcpy(ext, sep+1);
			strlwr(ext);
			if (!strstr(filter, sep+1)) goto next;
#endif
		}

#if defined(WIN32)
		file_info.hidden = (FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ? GF_TRUE : GF_FALSE;
		file_info.system = (FindData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? GF_TRUE : GF_FALSE;
		file_info.size = MAXDWORD;
		file_info.size += 1;
		file_info.size *= FindData.nFileSizeHigh;
		file_info.size += FindData.nFileSizeLow;
		file_info.last_modified = (u64) ((*(LONGLONG *) &FindData.ftLastWriteTime - TIMESPEC_TO_FILETIME_OFFSET) / 10000000);
#endif

#if defined (_WIN32_WCE)
		CE_WideToChar(FindData.cFileName, file);
		strcpy(item_path, _path);
		strcat(item_path, file);
#elif defined(WIN32)
		wcscpy(item_path, path);
		wcscat(item_path, FindData.cFileName);
		file = FindData.cFileName;
#else
		strcpy(item_path, path);
		strcat(item_path, the_file->d_name);
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] Checking file %s for enum\n", item_path));

		if (stat( item_path, &st ) != 0) goto next;

		file_info.directory = ((st.st_mode & S_IFMT) == S_IFDIR) ? GF_TRUE : GF_FALSE;
		if (enum_directory && !file_info.directory) goto next;
		if (!enum_directory && file_info.directory) goto next;

		file_info.size = st.st_size;

		{
			struct tm _t = * gmtime(& st.st_mtime);
			file_info.last_modified = mktime(&_t);
		}
		file = the_file->d_name;
		if (file && file[0]=='.') file_info.hidden = 1;

		if (file_info.directory) {
			char * parent_name = strrchr(item_path, '/');
			if (!parent_name) {
				file_info.drive = GF_TRUE;
			} else {
				struct stat st_parent;
				parent_name[0] = 0;
				if (stat(item_path, &st_parent) == 0)  {
					if ((st.st_dev != st_parent.st_dev) || ((st.st_dev == st_parent.st_dev) && (st.st_ino == st_parent.st_ino))) {
						file_info.drive = GF_TRUE;
					}
				}
				parent_name[0] = '/';
			}
		}
#endif

#ifdef WIN32
		mbs_file = wcs_to_utf8(file);
		mbs_item_path = wcs_to_utf8(item_path);
		if (!mbs_file || !mbs_item_path)
		{
			if (mbs_file) gf_free(mbs_file);
			if (mbs_item_path) gf_free(mbs_item_path);
			return GF_IO_ERR;
		}
		if (enum_dir_fct(cbck, mbs_file, mbs_item_path, &file_info)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(1) the following error code: %d\n", err));
			}
#else
		if (enum_dir_fct(cbck, file, item_path, &file_info)) {
#endif
			break;
		}

#ifdef WIN32
		gf_free(mbs_file);
		gf_free(mbs_item_path);
#endif

next:
#ifdef WIN32
		if (!FindNextFileW(SearchH, &FindData)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(2) the following error code: %d\n", err));
			}
			break;
		}
#else
		the_file = readdir(the_dir);
#endif
	}
#ifndef WIN32
	closedir(the_dir);
#endif
	return GF_OK;
}

GF_EXPORT
u64 gf_ftell(FILE *fp)
{
#if defined(_WIN32_WCE)
	return (u64) ftell(fp);
#elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) ftello64(fp);
#else
	return (u64) ftell(fp);
#endif
#elif defined(WIN32)
	return (u64) _ftelli64(fp);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return (u64) ftello64(fp);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return (u64) ftello(fp);
#else
	return (u64) ftell(fp);
#endif
}

GF_EXPORT
u64 gf_fseek(FILE *fp, s64 offset, s32 whence)
{
#if defined(_WIN32_WCE)
	return (u64) fseek(fp, (s32) offset, whence);
#elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) fseeko64(fp, offset, whence);
#else
	return (u64) fseek(fp, (s32) offset, whence);
#endif
#elif defined(WIN32)
	return (u64) _fseeki64(fp, offset, whence);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return fseeko64(fp, (off64_t) offset, whence);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return fseeko(fp, (off_t) offset, whence);
#else
	return fseek(fp, (s32) offset, whence);
#endif
}

GF_EXPORT
FILE *gf_fopen(const char *file_name, const char *mode)
{
	FILE *res = NULL;

#if defined(WIN32)
	wchar_t *wname;
	wchar_t *wmode;

	wname = utf8_to_wcs(file_name);
	wmode = utf8_to_wcs(mode);
	if (!wname || !wmode)
	{
		if (wname) gf_free(wname);
		if (wmode) gf_free(wmode);
		return NULL;
	}
	res = _wfsopen(wname, wmode, _SH_DENYNO);
	gf_free(wname);
	gf_free(wmode);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	res = fopen64(file_name, mode);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	res = fopen(file_name, mode);
#else
	res = fopen(file_name, mode);
#endif

	if (res) {
		gpac_file_handles++;
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] file %s opened in mode %s - %d file handles\n", file_name, mode, gpac_file_handles));
	} else {
		if (strchr(mode, 'w') || strchr(mode, 'a')) {
#if defined(WIN32)
			u32 err = GetLastError();
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: 0x%08x\n", file_name, mode, err));
#else
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: %d\n", file_name, mode, errno));
#endif
		}
	}
	return res;
}

GF_EXPORT
s32 gf_fclose(FILE *file)
{
	if (file) {
		assert(gpac_file_handles);
		gpac_file_handles--;
	}
	return fclose(file);
}

#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE) && !defined(WIN32)
#define HAVE_STRERROR_R 1
#endif

GF_EXPORT
size_t gf_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
	return fread(ptr, size, nmemb, stream);
}

GF_EXPORT
size_t gf_fwrite(const void *ptr, size_t size, size_t nmemb,
                 FILE *stream)
{
	size_t result = fwrite(ptr, size, nmemb, stream);
	if (result != nmemb) {
#ifdef _WIN32_WCE
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data: %d blocks to write but %d blocks written\n", nmemb, result));
#else
#if defined WIN32 && !defined(GPAC_CONFIG_WIN32)
		errno_t errno_save;
		_get_errno(&errno_save);
#else
		int errno_save = errno;
#endif
		//if (errno_save!=0)
		{
#ifdef HAVE_STRERROR_R
#define ERRSTR_BUF_SIZE 256
			char errstr[ERRSTR_BUF_SIZE];
			if(strerror_r(errno_save, errstr, ERRSTR_BUF_SIZE) != 0)
			{
				strerror_r(0, errstr, ERRSTR_BUF_SIZE);
			}
#else
			char *errstr = (char*)strerror(errno_save);
#endif
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data (%s): %d blocks to write but %d blocks written\n", errstr, nmemb, result));
		}
#endif
	}
	return result;
}
Exemple #6
0
int main( int argc, char** argv )
{
    FILE *file = NULL;
    uint8_t read_data;
    uint64_t fsize;
    int derp;

    /* Random stuff to calc changes */
    uint64_t last_sync_byte_pos[4];
    uint64_t differences[3];
    uint8_t counter = 0;
    uint64_t how_far = 0;

    /* Load the file and check its size. */
    file = fopen64( "herp.ts", "rb" );

    fseeko64( file, 0L, SEEK_END );
    fsize = ftello64( file );

    if(fsize == 0)
    {
        printf("Error: File size zero, not going further!");
        return 1;
    }

    rewind( file );

    /* Find the first sync byte. */
    do
    {
        derp = fread( &read_data, sizeof( uint8_t ), 1, file );
        if( derp != 1 )
        {
            printf("Error: Errored while reading a byte to find the first sync byte.");
            return 1;
        }
    } while( read_data != SYNC_BYTE );

    how_far = ( ftello64( file ) - 1);
    printf("Found first sync byte at: 0x%lX\n\n", how_far);

    printf("Trying to see if there is another sync byte in 188 bytes: ");

    fseeko64( file, 187L, SEEK_CUR );
    derp = fread( &read_data, sizeof( uint8_t ), 1, file );
    if( derp != 1 )
        return 1;

    if( read_data == SYNC_BYTE )
        printf("yes\n");
    else
        printf("no\n");

    printf("Trying to see if there is another sync byte in 192 bytes: ");

    fseeko64( file, 3L, SEEK_CUR );
    derp = fread( &read_data, sizeof( uint8_t ), 1, file );
    if( derp != 1 )
        return 1;

    if( read_data == SYNC_BYTE )
        printf("yes\n");
    else
        printf("no\n");

    printf("Trying to see if there is another sync byte in 204 bytes: ");

    fseeko64( file, 11L, SEEK_CUR );
    derp = fread( &read_data, sizeof( uint8_t ), 1, file );
    if( derp != 1 )
        return 1;

    if( read_data == SYNC_BYTE )
        printf("yes\n");
    else
        printf("no\n");

    return ( EXIT_SUCCESS );
}
Exemple #7
0
int pak_file_or_dir(struct dirent* dent, uint32_t idx, FILE* entryFile, FILE* stringFile, FILE* dataFile, bool compress, bool verbose)
{
    char tmppath[FILENAME_MAX];
    memcpy(tmppath, curpath, strlen(curpath) + 1);
    strcat(curpath, "/");
    strcat(curpath, dent->d_name);

    if ((time(NULL) - time_last) > 1 && !verbose)
    {
        printf(".");
        fflush(stdout);
        time_last = time(NULL);
    }

    struct stat64 st;
    stat64(curpath, &st);
    if (verbose)
        printf("%s\n", curpath);

    pak_entry_t* entry = pak_create_entry();

    if (S_ISLNK(st.st_mode))
        goto fail;

    if (!S_ISDIR(st.st_mode)) {

        FILE* in = fopen(curpath, "rb");
        if (in) {
            entry->flags = PAK_ENTRY_FLAGS_WRITEABLE;
            entry->file_id = idx;
            entry->string_offset = ftello64(stringFile);
            entry->data_offset_or_first_child = ftello64(dataFile);
            entry->data_size_or_child_count = st.st_size;
            entry->data_uncompressed_size = 0;

            idx++;

            fwrite(dent->d_name, 1, strlen(dent->d_name) + 1, stringFile);
            uint32_t data_len = st.st_size;
            char* buf = malloc(st.st_size);
            fread(buf, 1, st.st_size, in);

            if (compress) {
                void* comp_buf = malloc(data_len);
                size_t comp_len = util_compress(buf, st.st_size, comp_buf, Z_BEST_COMPRESSION);
                if (comp_len < (size_t)st.st_size) {
                    entry->flags |= PAK_ENTRY_FLAGS_COMPRESSED;
                    entry->data_uncompressed_size = st.st_size;
                    entry->data_size_or_child_count = comp_len;
                    data_len = (comp_len + 31) & ~31;
                    free(buf);
                    buf = malloc(data_len);
                    pak_clear(buf, data_len);
                    memcpy(buf, comp_buf, comp_len);
                    free(comp_buf);
                } else {
                    data_len = (data_len + 31) & ~31;
                    void* tmp = malloc(data_len);
                    pak_clear(tmp, data_len);
                    memcpy(tmp, buf, st.st_size);
                    free(buf);
                    buf = tmp;
                }
            }
            else
            {
                data_len = (data_len + 31) & ~31;
                void* tmp = malloc(data_len);
                pak_clear(tmp, data_len);
                memcpy(tmp, buf, st.st_size);
                free(buf);
                buf = tmp;
            }

            fwrite(entry, 1, sizeof(pak_entry_t), entryFile);
            fclose(in);
            fwrite(buf, 1, data_len, dataFile);
            free(buf);
        }

    } else if (S_ISDIR(st.st_mode)) {
        entry->flags = PAK_ENTRY_FLAGS_WRITEABLE | PAK_ENTRY_FLAGS_DIR;
        entry->file_id = idx;
        entry->string_offset = ftello64(stringFile);
        entry->data_offset_or_first_child = idx + 1;
        entry->data_size_or_child_count = 0;
        idx++;

        fwrite(dent->d_name, 1, strlen(dent->d_name) + 1, stringFile);
        uint32_t offset = ftello64(entryFile);
        fseeko64(entryFile, sizeof(pak_entry_t), SEEK_CUR);
        DIR* thisDir = opendir(curpath);
        if (thisDir) {   struct dirent * child = NULL;
            while ((child = readdir(thisDir)) != NULL) {
                if (!strcmp(child->d_name, ".") || !strcmp(child->d_name, "..") || !strcmp(child->d_name, ".git"))
                    continue;

                idx = pak_file_or_dir(child, idx, entryFile, stringFile, dataFile, compress, verbose);
                entry->data_size_or_child_count++;
            }
            if (!entry->data_size_or_child_count)
                entry->data_offset_or_first_child = 0;
        }

        fseeko64(entryFile, offset, SEEK_SET);
        fwrite(entry, 1, sizeof(pak_entry_t), entryFile);
        fseeko64(entryFile, 0, SEEK_END);

    }
    else if (verbose)
fail:
        printf("skipped\n");

    strcpy(curpath, tmppath);
    pak_free_entry(entry);

    return idx;
}
Exemple #8
0
NV_INT32 image_read_header (FILE *fp, IMAGE_HEADER_T *head)
{
  NV_INT32    ret;
  NV_INT64    long_pos;
  NV_CHAR     varin[1024], info[1024];

  NV_CHAR *ngets (NV_CHAR *s, NV_INT32 size, FILE *stream);
  NV_INT32 big_endian ();


  swap = NVFalse;


  /*  Check for the new format file.  If the first four characters are 
      "File" it's the new format, otherwise read the binary header.  */

  fseeko64 (fp, 0LL, SEEK_SET);
  ngets (varin, sizeof (varin), fp);

  if (!strncmp (varin, "File", 4))
    {
      fseeko64 (fp, 0LL, SEEK_SET);


      /*  Read each entry.    */

      head->text.header_size = 0;
      while (ngets (varin, sizeof (varin), fp) != NULL)
        {
          if (!strcmp (varin, "EOF")) break;


          /*  Put everything to the right of the colon into 'info'.   */
            
          if (strchr (varin, ':') != NULL) strcpy (info, (NV_CHAR *) (strchr (varin, ':') + 1));


          /*  Check input for matching strings and load values if found.  */
            
          if (strstr (varin, "FileType:") != NULL) lidar_get_string (varin, head->text.file_type);

          if (strstr (varin, "EndianType:") != NULL)
            {
              if (strstr (info, "Little"))
                {
                  head->text.endian = NVFalse;
                  if (big_endian ()) swap = NVTrue;
                }
              else
                {
                  head->text.endian = NVTrue;
                  if (!big_endian ()) swap = NVTrue;
                }
            }


          if (strstr (varin, "SoftwareVersionNumber:") != NULL) sscanf (info, "%f", &head->text.software_version);

          if (strstr (varin, "FileVersionNumber:") != NULL) sscanf (info, "%f", &head->text.file_version);


          if (strstr (varin, "Downloaded By:") != NULL) lidar_get_string (varin, head->text.UserName);


          if (strstr (varin, "HeaderSize:") != NULL) sscanf (info, "%d", &head->text.header_size);

          if (strstr (varin, "TextBlockSize:") != NULL) sscanf (info, "%d", &head->text.text_block_size);

          if (strstr (varin, "BinaryBlockSize:") != NULL) sscanf (info, "%d", &head->text.bin_block_size);


          if (strstr (varin, "Project:") != NULL) lidar_get_string (varin, head->text.project);

          if (strstr (varin, "Mission:") != NULL) lidar_get_string (varin, head->text.mission);

          if (strstr (varin, "Dataset:") != NULL) lidar_get_string (varin, head->text.dataset);

          if (strstr (varin, "FlightlineNumber:") != NULL) lidar_get_string (varin, head->text.flightline_number);

          if (strstr (varin, "CodedFLNumber:") != NULL) sscanf (info, "%hd", &head->text.coded_fl_number);

          if (strstr (varin, "FlightDate:") != NULL) lidar_get_string (varin, head->text.flight_date);

          if (strstr (varin, "StartTime:") != NULL) lidar_get_string (varin, head->text.start_time);

          if (strstr (varin, "EndTime:") != NULL) lidar_get_string (varin, head->text.end_time);

          if (strstr (varin, "StartTimestamp:") != NULL) sscanf (info, NV_INT64_SPECIFIER, &head->text.start_timestamp);

          if (strstr (varin, "EndTimestamp:") != NULL) sscanf (info, NV_INT64_SPECIFIER, &head->text.end_timestamp);

          if (strstr (varin, "NumberImages:") != NULL) sscanf (info, "%d", &head->text.number_images);

          if (strstr (varin, "IndexRecordSize:") != NULL) sscanf (info, "%d", &head->text.record_size);

          if (strstr (varin, "IndexBlockSize:") != NULL) sscanf (info, "%d", &head->text.block_size);

          if (strstr (varin, "FileCreateDate:") != NULL) lidar_get_string (varin, head->text.dataset_create_date);

          if (strstr (varin, "FileCreateTime:") != NULL) lidar_get_string (varin, head->text.dataset_create_time);

          long_pos = ftello64 (fp);
          if (head->text.header_size && long_pos >= head->text.header_size) break;
        }


      /*  Make sure we're past the header.  */

      fseeko64 (fp, (NV_INT64) head->text.header_size, SEEK_SET);

      ret = 0;
    }
  else
    {
      /*  Early versions were screwed up.  */

      fseeko64 (fp, (NV_INT64) IMAGE_HEAD_SIZE, SEEK_SET);

      fread (&head->info, sizeof (IMAGE_INFO_T), 1, fp);


      /*  Swap the INFO block if needed.  */

      if (swap) swap_image_header (&head->info);


      head->text.start_timestamp = head->info.start_timestamp;
      head->text.end_timestamp = head->info.end_timestamp;
      head->text.number_images = head->info.number_images;

      ret = 1;
    }


  head->text.data_size = l_head.text.data_size;


  return (ret);
}
Exemple #9
0
/*enumerate directories*/
GF_EXPORT
GF_Err gf_enum_directory(const char *dir, Bool enum_directory, gf_enum_dir_item enum_dir_fct, void *cbck, const char *filter)
{
	char item_path[GF_MAX_PATH];
	GF_FileEnumInfo file_info;

#if defined(_WIN32_WCE)
	char _path[GF_MAX_PATH];
	unsigned short path[GF_MAX_PATH];
	unsigned short w_filter[GF_MAX_PATH];
	char file[GF_MAX_PATH];
#else
	char path[GF_MAX_PATH], *file;
#endif

#ifdef WIN32
	WIN32_FIND_DATA FindData;
	HANDLE SearchH;
#else
	DIR *the_dir;
	struct dirent* the_file;
	struct stat st;
#endif

	if (!dir || !enum_dir_fct) return GF_BAD_PARAM;

	if (filter && (!strcmp(filter, "*") || !filter[0])) filter=NULL;

	memset(&file_info, 0, sizeof(GF_FileEnumInfo) );

	if (!strcmp(dir, "/")) {
#if defined(WIN32) && !defined(_WIN32_WCE)
		u32 len;
		char *drives, *volume;
		len = GetLogicalDriveStrings(0, NULL);
		drives = (char*)gf_malloc(sizeof(char)*(len+1));
		drives[0]=0;
		GetLogicalDriveStrings(len, drives);
		len = (u32) strlen(drives);
		volume = drives;
		file_info.directory = GF_TRUE;
		file_info.drive = GF_TRUE;
		while (len) {
			enum_dir_fct(cbck, volume, "", &file_info);
			volume += len+1;
			len = (u32) strlen(volume);
		}
		gf_free(drives);
		return GF_OK;
#elif defined(__SYMBIAN32__)
		RFs iFs;
		TDriveList aList;
		iFs.Connect();
		iFs.DriveList(aList);
		for (TInt i=0; i<KMaxDrives; i++) {
			if (aList[i]) {
				char szDrive[10];
				TChar aDrive;
				iFs.DriveToChar(i, aDrive);
				sprintf(szDrive, "%c:", (TUint)aDrive);
				enum_dir_fct(cbck, szDrive, "", &file_info);
			}
		}
		iFs.Close();
		FlushItemList();
		return GF_OK;
#endif
	}


#if defined (_WIN32_WCE)
	switch (dir[strlen(dir) - 1]) {
	case '/':
	case '\\':
		sprintf(_path, "%s*", dir);
		break;
	default:
		sprintf(_path, "%s%c*", dir, GF_PATH_SEPARATOR);
		break;
	}
	CE_CharToWide(_path, path);
	CE_CharToWide((char *)filter, w_filter);
#elif defined(WIN32)
	switch (dir[strlen(dir) - 1]) {
	case '/':
	case '\\':
		sprintf(path, "%s*", dir);
		break;
	default:
		sprintf(path, "%s%c*", dir, GF_PATH_SEPARATOR);
		break;
	}
#else
	strcpy(path, dir);
	if (path[strlen(path)-1] != '/') strcat(path, "/");
#endif

#ifdef WIN32
	SearchH= FindFirstFile(path, &FindData);
	if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR;

#if defined (_WIN32_WCE)
	_path[strlen(_path)-1] = 0;
#else
	path[strlen(path)-1] = 0;
#endif

	while (SearchH != INVALID_HANDLE_VALUE) {

#else

	the_dir = opendir(path);
	if (the_dir == NULL) {
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot open directory %s for enumeration: %d\n", path, errno));
		return GF_IO_ERR;
	}
	the_file = readdir(the_dir);
	while (the_file) {

#endif

		memset(&file_info, 0, sizeof(GF_FileEnumInfo) );


#if defined (_WIN32_WCE)
		if (!wcscmp(FindData.cFileName, _T(".") )) goto next;
		if (!wcscmp(FindData.cFileName, _T("..") )) goto next;
#elif defined(WIN32)
		if (!strcmp(FindData.cFileName, ".")) goto next;
		if (!strcmp(FindData.cFileName, "..")) goto next;
#else
		if (!strcmp(the_file->d_name, "..")) goto next;
		if (the_file->d_name[0] == '.') goto next;
#endif

#ifdef WIN32
		file_info.directory = (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? GF_TRUE : GF_FALSE;
		if (!enum_directory && file_info.directory) goto next;
		if (enum_directory && !file_info.directory) goto next;
#endif

		if (filter) {
#if defined (_WIN32_WCE)
			short ext[30];
			short *sep = wcsrchr(FindData.cFileName, (wchar_t) '.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#elif defined(WIN32)
			char ext[30];
			char *sep = strrchr(FindData.cFileName, '.');
			if (!sep) goto next;
			strcpy(ext, sep+1);
			strlwr(ext);
			if (!strstr(filter, ext)) goto next;
#else
			char ext[30];
			char *sep = strrchr(the_file->d_name, '.');
			if (!sep) goto next;
			strcpy(ext, sep+1);
			strlwr(ext);
			if (!strstr(filter, sep+1)) goto next;
#endif
		}

#if defined(WIN32)
		file_info.hidden = (FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ? GF_TRUE : GF_FALSE;
		file_info.system = (FindData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? GF_TRUE : GF_FALSE;
		file_info.size = MAXDWORD;
		file_info.size += 1;
		file_info.size *= FindData.nFileSizeHigh;
		file_info.size += FindData.nFileSizeLow;
		file_info.last_modified = (u64) ((*(LONGLONG *) &FindData.ftLastWriteTime - TIMESPEC_TO_FILETIME_OFFSET) / 10000000);
#endif

#if defined (_WIN32_WCE)
		CE_WideToChar(FindData.cFileName, file);
		strcpy(item_path, _path);
		strcat(item_path, file);
#elif defined(WIN32)
		strcpy(item_path, path);
		strcat(item_path, FindData.cFileName);
		file = FindData.cFileName;
#else
		strcpy(item_path, path);
		strcat(item_path, the_file->d_name);
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] Checking file %s for enum\n", item_path));

		if (stat( item_path, &st ) != 0) goto next;

		file_info.directory = ((st.st_mode & S_IFMT) == S_IFDIR) ? GF_TRUE : GF_FALSE;
		if (enum_directory && !file_info.directory) goto next;
		if (!enum_directory && file_info.directory) goto next;

		file_info.size = st.st_size;

		{
			struct tm _t = * gmtime(& st.st_mtime);
			file_info.last_modified = mktime(&_t);
		}
		file = the_file->d_name;
		if (file && file[0]=='.') file_info.hidden = 1;

		if (file_info.directory) {
			char * parent_name = strrchr(item_path, '/');
			if (!parent_name) {
				file_info.drive = GF_TRUE;
			} else {
				struct stat st_parent;
				parent_name[0] = 0;
				if (stat(item_path, &st_parent) == 0)  {
					if ((st.st_dev != st_parent.st_dev) || ((st.st_dev == st_parent.st_dev) && (st.st_ino == st_parent.st_ino))) {
						file_info.drive = GF_TRUE;
					}
				}
				parent_name[0] = '/';
			}
		}
#endif
		if (enum_dir_fct(cbck, file, item_path, &file_info)) {
#ifdef WIN32
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(1) the following error code: %d\n", err));
			}
#endif
			break;
		}

next:
#ifdef WIN32
		if (!FindNextFile(SearchH, &FindData)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(2) the following error code: %d\n", err));
			}
			break;
		}
#else
		the_file = readdir(the_dir);
#endif
	}
#ifndef WIN32
	closedir(the_dir);
#endif
	return GF_OK;
}

GF_EXPORT
u64 gf_ftell(FILE *fp)
{
#if defined(_WIN32_WCE)
	return (u64) ftell(fp);
#elif defined(GPAC_CONFIG_WIN32)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) ftello64(fp);
#else
	return (u64) ftell(fp);
#endif
#elif defined(WIN32)
	return (u64) _ftelli64(fp);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return (u64) ftello64(fp);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return (u64) ftello(fp);
#else
	return (u64) ftell(fp);
#endif
}

GF_EXPORT
u64 gf_fseek(FILE *fp, s64 offset, s32 whence)
{
#if defined(_WIN32_WCE)
	return (u64) fseek(fp, (s32) offset, whence);
#elif defined(GPAC_CONFIG_WIN32)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) fseeko64(fp, offset, whence);
#else
	return (u64) fseek(fp, (s32) offset, whence);
#endif
#elif defined(WIN32)
	return (u64) _fseeki64(fp, offset, whence);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return fseeko64(fp, (off64_t) offset, whence);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return fseeko(fp, (off_t) offset, whence);
#else
	return fseek(fp, (s32) offset, whence);
#endif
}

GF_EXPORT
FILE *gf_fopen(const char *file_name, const char *mode)
{
	FILE *res;

#if defined(WIN32)
	res = fopen(file_name, mode);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	res = fopen64(file_name, mode);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	res = fopen(file_name, mode);
#else
	res = fopen(file_name, mode);
#endif

	if (res) {
		gpac_file_handles ++;
	} else {
		if (strchr(mode, 'w') || strchr(mode, 'a')) {
#if defined(WIN32)
			u32 err = GetLastError();
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: 0x%08x\n", file_name, mode, err));
#else
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: %d\n", file_name, mode, errno));
#endif
		}
	}
	return res;
}
Exemple #10
0
static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
{
    ZPOS64_T ret;
    ret = ftello64((FILE *)stream);
    return ret;
}
int main (int argc, char *argv[]) {

        FILE *LINKDBFILE;
        FILE *INDEXFILE;

	struct ipdbl ipdbha;

	int count;
        int ranged;
        struct linkdb_block linkdbPost;
	unsigned int DocID;
	off64_t offset;
        unsigned int lastDocID;
	unsigned int ipadress;

	struct popl popha;
	int rank;

        if (argc < 4) {
                printf("Dette programet tar inn en MainLinkDB, linkdbindex og DocID query får søk\n\n\tUsage: ./searchIndexLinkdb MainLinkDB linkdbindex DocID\n");
                exit(0);
        }

        if ((LINKDBFILE = (FILE *)fopen64(argv[1],"rb")) == NULL) {
                printf("Cant read linkdb ");
                perror(argv[1]);
                exit(1);
        }


        if ((INDEXFILE = fopen(argv[2],"rb")) == NULL) {
                printf("Cant read index ");
                perror(argv[2]);
                exit(1);
        }

	popopen (&popha, "/home/boitho/config/popindex");
	ipdbOpen(&ipdbha);

	DocID = atol(argv[3]);

	printf("links ti %lu:\n",DocID);

	rank =  popRankForDocID(&popha,DocID);
        ipadress = ipdbForDocID(&ipdbha,DocID);

	printf("rank %i, ipadress %u\n",rank,ipadress);

	//finner offset
	fseek(INDEXFILE,DocID * sizeof(offset),SEEK_SET);
	fread(&offset,sizeof(offset),1,INDEXFILE);
	printf("offset: %llu\n",offset);

	printf("offset: %" PRId64 "\n",offset);

	//søker til offsetten
	if(fseeko64(LINKDBFILE,offset,SEEK_SET) == -1) {
		perror("seek");
		exit(1);
	}

	printf("søkte til %" PRId64 "\n",ftello64(LINKDBFILE));

	count = 0;
        while (!feof(LINKDBFILE)) {


                if (fread(&linkdbPost,sizeof(linkdbPost),1,LINKDBFILE) == 0) {
			perror("read");
			exit(1);
		}

		rank =  popRankForDocID(&popha,linkdbPost.DocID_from);		
		ipadress = ipdbForDocID(&ipdbha,linkdbPost.DocID_from);

		if (linkdbPost.DocID_to == DocID) {
			printf("%u (r %i, ip %u)-> %u\n",linkdbPost.DocID_from,rank,ipadress,linkdbPost.DocID_to);
		}
		else {
			printf("end %u\n",linkdbPost.DocID_to);
			printf("last: %u -> %u\n",linkdbPost.DocID_from,linkdbPost.DocID_to);
			break;
		}

		++count;
	}

	popclose(&popha);

	ipdbClose(&ipdbha);

	fclose(LINKDBFILE);
	fclose(INDEXFILE);
	
	printf("%i links\n",count);
}
int main (int argc, char *argv[]) {

	FILE *LINKDBFILE;
	FILE *INDEXFILE;

	unsigned int ranged;
	struct linkdb_block linkdbPost;
	off64_t offset;
	int lastLotNr, lotNr = -1;


	unsigned int lastDocID;


        if (argc < 3) {
                printf("Dette programet tar inn en linkdb fil og gjør den søkbar\n\n\tUsage: ./BrankCalculate linkdb indexfile\n");
                exit(0);
        }

	if ((LINKDBFILE = (FILE *)fopen64(argv[1],"rb")) == NULL) {
                printf("Cant read linkdb ");
                perror(argv[1]);
                exit(1);
        }
	if ((INDEXFILE = (FILE *)fopen64(argv[2],"wb")) == NULL) {
                printf("Cant read index ");
                perror(argv[2]);
                exit(1);
        }

	ranged = 0;
	lastDocID = 0;
	while (!feof(LINKDBFILE)) {


			fread(&linkdbPost,sizeof(linkdbPost),1,LINKDBFILE);


				//
				lotNr = rLotForDOCid(linkdbPost.DocID_to);
				if (lastLotNr != lotNr) {
					printf("%i\n",lotNr);
				}
				lastLotNr = lotNr;



			if (linkdbPost.DocID_to != lastDocID) {
				//printf("\nnew\n");

				//tar vare på ofsett // -sizeof(offset) da vi skal ha starten. Vi har jo allerede lest en
				//offset = (ftello64(LINKDBFILE) - sizeof(linkdbPost));
				offset = ftello64(LINKDBFILE);
				//printf("offset %li\n",offset);
				//søker oss til riktig plass
				fseeko64(INDEXFILE,linkdbPost.DocID_to * sizeof(offset),SEEK_SET);
				//for så å skrive dette til fil
				fwrite(&offset,sizeof(offset),1,INDEXFILE);

			}

			//printf("%u -> %u\n",linkdbPost.DocID_from,linkdbPost.DocID_to);

			
			lastDocID = linkdbPost.DocID_to;

			//if (ranged > 500) {
			//	break;
			//}

		++ranged;

	}	



	fclose(LINKDBFILE);
	fclose(INDEXFILE);
	printf("Rangerte %lu linker\n",ranged);
}
Exemple #13
0
edk::uint64 File::getSeek64(){
    return ftello64(this->arq);
}
/* Retrieves the current offset in the file stream
 * This function uses the POSIX ftello function or equivalent
 * Returns 1 if successful or -1 on error
 */
int libcfile_stream_get_offset(
     libcfile_stream_t *stream,
     off64_t *offset,
     libcerror_error_t **error )
{
	libcfile_internal_stream_t *internal_stream = NULL;
	static char *function                       = "libcfile_stream_get_offset";

	if( stream == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid stream.",
		 function );

		return( -1 );
	}
	internal_stream = (libcfile_internal_stream_t *) stream;

	if( internal_stream->stream == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_MISSING,
		 "%s: invalid stream - missing stream.",
		 function );

		return( -1 );
	}
	if( offset == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid offset.",
		 function );

		return( -1 );
	}
#if defined( WINAPI )
	*offset = (off64_t) ftell(
	                     internal_stream->stream );
#elif defined( HAVE_FTELLO64 ) && !defined( HAVE_FTELLO )
	*offset = ftello64(
	           internal_stream->stream );
#else
	*offset = (off64_t) ftello(
	                     internal_stream->stream );
#endif
	if( *offset < 0 )
	{
		libcerror_system_set_error(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 errno,
		 "%s: unable to get offset from stream.",
		 function );

		return( -1 );
	}
	return( 1 );
}
/* Seeks a certain offset within the file stream
 * This function uses the POSIX fseeko and ftello functions or equivalent
 * Returns the offset if the seek is successful or -1 on error
 */
off64_t libcfile_stream_seek_offset(
         libcfile_stream_t *stream,
         off64_t offset,
         int whence,
         libcerror_error_t **error )
{
	libcfile_internal_stream_t *internal_stream = NULL;
	static char *function                       = "libcfile_stream_seek_offset";
	int result                                  = 0;

	if( stream == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid stream.",
		 function );

		return( -1 );
	}
	internal_stream = (libcfile_internal_stream_t *) stream;

	if( internal_stream->stream == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_MISSING,
		 "%s: invalid stream - missing stream.",
		 function );

		return( -1 );
	}
#if defined( WINAPI ) && ( LONG_MAX < INT64_MAX )
	if( offset > (off64_t) LONG_MAX )
#else
	if( offset > (off64_t) INT64_MAX )
#endif
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
		 "%s: invalid offset value exceeds maximum.",
		 function );

		return( -1 );
	}
	if( ( whence != SEEK_CUR )
	 && ( whence != SEEK_END )
	 && ( whence != SEEK_SET ) )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE,
		 "%s: unsupported whence.",
		 function );

		return( -1 );
	}
#if defined( WINAPI )
	result = fseek(
	          internal_stream->stream,
	          (long) offset,
	          whence );
#elif defined( HAVE_FSEEKO64 ) && !defined( HAVE_FSEEKO )
	result = fseeko64(
	          internal_stream->stream,
	          offset,
	          whence );
#else
	result = fseeko(
	          internal_stream->stream,
	          (off_t) offset,
	          whence );
#endif
	if( result != 0 )
	{
		libcerror_system_set_error(
		 error,
		 LIBCERROR_ERROR_DOMAIN_IO,
		 LIBCERROR_IO_ERROR_SEEK_FAILED,
		 errno,
		 "%s: unable to seek offset in stream.",
		 function );

		return( -1 );
	}
#if defined( WINAPI )
	offset = (off64_t) ftell(
	                    internal_stream->stream );
#elif defined( HAVE_FTELLO64 ) && !defined( HAVE_FTELLO )
	offset = ftello64(
	          internal_stream->stream );
#else
	offset = (off64_t) ftello(
	                    internal_stream->stream );
#endif
	if( offset < 0 )
	{
		libcerror_system_set_error(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 errno,
		 "%s: unable to get offset from stream.",
		 function );

		return( -1 );
	}
	return( offset );
}
Exemple #16
0
int     DownloadPartition   (libusb_device_handle *handle, char *fid,
                            uint32_t sector, uint32_t sectors = 0)
{
    char    *buf = (char*) malloc (65536);
    FILE    *fin;
    off64_t file_size;
    uint    file_sectors;
    uint    nand_sec_size = 512;
    uint    usb_rec_size, usb_rec_secs;
    uint    read_bytes, read_secs, bytes_read;
    uint    sector_key, sector_limit;
    uint    usb_flags;

    usb_rec_size = 65536;
    usb_rec_secs = usb_rec_size / nand_sec_size;
    usb_rec_size = usb_rec_secs * nand_sec_size;

    if (NULL == (fin = fopen64 (fid, "rb"))) {
        perror("Failed to open file to send: ");
        exit(1);
    }

//  aw_fes_send_file (handle, MagicAddr, AW_FEL2_DRAM, FN->magic_cr_start);      // not when A10

    printf ("Sending %s...", fid);
    fflush (stdout);

    fseeko64 (fin, 0, SEEK_END);
    file_size = ftello64 (fin);
    file_sectors = (file_size + nand_sec_size - 1) / nand_sec_size;
    fseeko64 (fin, 0, SEEK_SET);

    sector_key = sector;
    if (sectors < file_sectors)
        sectors = file_sectors;
    sector_limit = sector_key + sectors;

    while (sector_key < sector_limit)
      {
        read_secs = sector_limit - sector_key;
        if (read_secs > usb_rec_secs)
            read_secs = usb_rec_secs;
        read_bytes = read_secs * nand_sec_size;

        bytes_read = fread (buf, 1, read_bytes, fin);
        if (bytes_read < read_bytes)
            PutNulls (buf + bytes_read, read_bytes - bytes_read);

        usb_flags = AW_FEL2_NAND | AW_FEL2_WR;
        if (sector_key == sector)
            usb_flags |= AW_FEL2_FIRST;
        if (sector_key + read_secs == sector_limit)
            usb_flags |= AW_FEL2_LAST;
        aw_fes_write (handle, sector_key, buf, read_bytes, usb_flags);
//printf ("sector = %d, sector_key = %d, read_secs = %d, sector_limit = %d, flags = %x\n", sector, sector_key, read_secs, sector_limit, usb_flags);

        sector_key += read_secs;
      }

    printf ("done\n");
    fclose (fin);

//  aw_fes_send_file (handle, MagicAddr, AW_FEL2_DRAM, FN->magic_cr_end);        // not when A10

    free (buf);

    return 0;
}