コード例 #1
0
ファイル: filesenddlg.cpp プロジェクト: gloria8023/miranda-ng
static void SetFileListAndSizeControls(HWND hwndDlg, FileDlgData *dat)
{
	int fileCount = 0, dirCount = 0, i;
	__int64 totalSize = 0;
	struct _stati64 statbuf;
	TCHAR str[64];

	for (i = 0; dat->files[i]; i++) {
		if (_tstati64(dat->files[i], &statbuf) == 0) {
			if (statbuf.st_mode & _S_IFDIR)
				dirCount++;
			else
				fileCount++;
			totalSize += statbuf.st_size;
		}
	}

	GetSensiblyFormattedSize(totalSize, str, _countof(str), 0, 1, NULL);
	SetDlgItemText(hwndDlg, IDC_TOTALSIZE, str);
	if (i > 1) {
		TCHAR szFormat[32];
		if (fileCount && dirCount) {
			mir_sntprintf(szFormat, _T("%s, %s"), TranslateTS(fileCount == 1 ? _T("%d file") : _T("%d files")), TranslateTS(dirCount == 1 ? _T("%d directory") : _T("%d directories")));
			mir_sntprintf(str, szFormat, fileCount, dirCount);
		}
		else if (fileCount) {
			mir_tstrcpy(szFormat, TranslateT("%d files"));
			mir_sntprintf(str, szFormat, fileCount);
		}
		else {
			mir_tstrcpy(szFormat, TranslateT("%d directories"));
			mir_sntprintf(str, szFormat, dirCount);
		}
		SetDlgItemText(hwndDlg, IDC_FILE, str);
	}
	else SetDlgItemText(hwndDlg, IDC_FILE, dat->files[0]);

	EnableWindow(GetDlgItem(hwndDlg, IDOK), fileCount || dirCount);
}
コード例 #2
0
ファイル: proto.cpp プロジェクト: martok/miranda-ng
int __cdecl CAimProto::FileResume(HANDLE hTransfer, int* action, const PROTOCHAR** szFilename)
{
	file_transfer *ft = (file_transfer*)hTransfer;
	if (!ft_list.find_by_ft(ft)) return 0;

	switch (*action)
	{
	case FILERESUME_RESUME:
		{
			struct _stati64 statbuf;
			_tstati64(ft->pfts.tszCurrentFile, &statbuf);
			ft->pfts.currentFileProgress = statbuf.st_size;
		}
		break;

	case FILERESUME_RENAME:
		mir_free(ft->pfts.tszCurrentFile);
		ft->pfts.tszCurrentFile = mir_tstrdup(*szFilename);
		break;

	case FILERESUME_OVERWRITE:
		ft->pfts.currentFileProgress = 0;
		break;

	case FILERESUME_SKIP:
		mir_free(ft->pfts.tszCurrentFile);
		ft->pfts.tszCurrentFile = NULL;
		break;

	default:
		aim_file_ad(hServerConn, seqno, ft->sn, ft->icbm_cookie, true, ft->max_ver);
		break;
	}
	SetEvent(ft->hResumeEvent);

	return 0;
}
コード例 #3
0
ファイル: file.cpp プロジェクト: Seldom/miranda-ng
bool setup_next_file_send(file_transfer *ft)
{
	TCHAR *file;
	struct _stati64 statbuf;
	for (;;) {
		file = ft->pfts.ptszFiles[ft->cf];
		if (file == NULL) return false;

		if (_tstati64(file, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) == 0)
			break;

		++ft->cf;
	}

	ft->pfts.tszCurrentFile = file;
	ft->pfts.currentFileSize = statbuf.st_size;
	ft->pfts.currentFileTime = statbuf.st_mtime;
	ft->pfts.currentFileProgress = 0;

	char* fnamea;
	T2Utf fname(file);
	if (ft->pfts.totalFiles > 1 && ft->file[0]) {
		size_t dlen = mir_strlen(ft->file);
		if (strncmp(fname, ft->file, dlen) == 0 && fname[dlen] == '\\') {
			fnamea = &fname[dlen + 1];
			for (char *p = fnamea; *p; ++p)
				if (*p == '\\')
					*p = 1;
		}
		else fnamea = get_fname(fname);
	}
	else fnamea = get_fname(fname);

	send_init_oft2(ft, fnamea);
	return true;
}
コード例 #4
0
ファイル: UnzProc.cpp プロジェクト: geoffsmith82/delphizip
/* ===========================================================================
 *                     Function do_seekable()
 * return PK-type error code */
int UnzOpr::do_seekable(int lastchance)
{
	/* static int no_ecrec = FALSE;  SKM: moved to globals.h */
	ulg sig;
	struct stati64 stt64;
	int maybe_exe = false;
	int too_weird_to_continue = false;
	int error = 0, error_in_archive;

	if (Verbose < 0)
		Notify(ITRACE, _T("starting do_seekable"));

	/* ---------------------------------------------------------------------------
	 * Open the zipfile for reading in BINARY mode to prevent CR/LF translation,
	 * which would corrupt the bit streams.
	 *--------------------------------------------------------------------------- */
	if (_tstati64(fzipfn.c_str(), &stt64) || (error = S_ISDIR(stt64.st_mode)) != 0)
		return error ? IZ_DIR : PK_NOZIP;

	fziplen = stt64.st_size;

	if (stt64.st_mode & S_IEXEC)
		maybe_exe = true;
	/* might find unzip, not unzip.zip; etc. */

	if (Verbose) // < 0)
		Notify(ITRACE, _T("opening zip file; fname=%s"), fzipfn.c_str());
	fUnzInfile = NULL;
	AutoStream uzfile(&fUnzInfile);

	fUnzInfile = new ZFile(this, fzipfn,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS);
	if (!uzfile.Stream()->IsOpen())
	{
		if (Verbose < 0)
			Notify(ITRACE, _T("could not open: %s [%s]"), fzipfn.c_str(),
			SysMsg().c_str());

		throw DZException(DZ_ERM_ERROR_CREATE);
	}

	if (Verbose < 0)
		Notify(ITRACE, _T("zip file %s opened OK"), fzipfn.c_str());
	/* the stat() test above, but... */
	// if (Verbose < 0)
	// Notify(ITRACE, "do_seekable, loc 3");

	/* ---------------------------------------------------------------------------
	 * Find and process the end-of-central-directory header.  UnZip need only
	 * check last 65557 bytes of zipfile:  comment may be up to 65535, end-of-
	 * central-directory record is 18 bytes, and signature itself is 4 bytes;
	 * add some to allow for appended garbage.
	 *--------------------------------------------------------------------------- */

	fcur_zipfile_bufstart = 0;
	finptr = finbuf;

#ifdef TIMESTAMP
	if (!fqflag && !fT_flag)
#else
		if (!fqflag)
#endif

			Notify(0, _T("Archive:  %s"), fzipfn.c_str());

	if (Verbose < 0)
		Notify(ITRACE, _T("do_seekable, loc 4"));
	if ((((error_in_archive = find_ecrec(MIN(fziplen, 66000L))) != 0 ||
				((error_in_archive = uz_end_central()) != 0 && DZ_ERR
					(error_in_archive) != PK_WARN))))
	{
		delete fUnzInfile;
		fUnzInfile = NULL;

		if (maybe_exe)
			Notify(0, _T("maybe an EXE file: %s"), fzipfn.c_str());
		if (lastchance)
			return error_in_archive;
		else
		{
			fno_ecrec = true;
			/* assume we found wrong file:  e.g., */
			return PK_NOZIP;
			/* unzip instead of unzip.zip */
		}
	}

	if (Verbose < 0)
		Notify(ITRACE, _T("do_seekable, loc 5"));
	if (fzflag > 0)
	{
		delete fUnzInfile;
		fUnzInfile = NULL;
		return error_in_archive;
	}

	/* ---------------------------------------------------------------------------
	 * Test the end-of-central-directory info for incompatibilities (multi-disk
	 * archives) or inconsistencies (missing or extra bytes in zipfile).
	 *--------------------------------------------------------------------------- */
#ifdef NO_MULTIPART
	error = (fecrec.number_this_disk == 1) && (fecrec.num_disk_start_cdir == 1);
#else
	error = (fecrec.number_this_disk != 0);
#endif
#ifdef NO_MULTIPART /* concatenation of multiple parts works in some cases */
	// else
	if (!error && fecrec.number_this_disk != 0)
	{
		DZError(DZ_ERM_ZIP_MULTI);
		error_in_archive = PK_FIND;
		too_weird_to_continue = true;
	}
#endif

	if (Verbose < 0)
		Notify(ITRACE, _T("do_seekable, loc 6"));
	if (!too_weird_to_continue)
	{
		/* (relatively) normal zipfile:  go for it */
		if (error)
		{
			Notify(0, _T("maybe a pak bug in %s"), fzipfn.c_str());
			error_in_archive = PK_WARN;
		}

		if ((fextra_bytes = freal_ecrec_offset - fexpect_ecrec_offset) < 0L)
		{
			Notify(0, _T("missing bytes in zipfile"));
			error_in_archive = PK_ERR;
		}
		else if (fextra_bytes > 0)
		{
			if ((fecrec.offset_start_central_directory == 0) &&
				(fecrec.size_central_directory != 0))
			{
				/* zip 1.5 -go bug */
				Notify(0, _T("NULL central dir"));
				fecrec.offset_start_central_directory = fextra_bytes;
				fextra_bytes = 0;
				error_in_archive = PK_ERR;
			}
			else
			{
				Notify(0, _T("Warning: extra bytes at start of zipfile"));
				error_in_archive = PK_WARN;
			}
		}

		/* -----------------------------------------------------------------------
		 *       Check for empty zipfile and exit now if so.
		 *----------------------------------------------------------------------- */
		if (Verbose < 0)
			Notify(ITRACE, _T("do_seekable, loc 7"));
		if (fexpect_ecrec_offset == 0L && fecrec.size_central_directory == 0)
		{
			Notify(0, _T("Empty zipfile"));
			delete fUnzInfile;
			fUnzInfile = NULL;
			return PK_ERR_NOWARN(error_in_archive) ? error_in_archive : PK_WARN;
		}

		/* -----------------------------------------------------------------------
		 * Compensate for missing or extra bytes, and seek to where the start
		 * of central directory should be.  If header not found, uncompensate
		 * and try again (necessary for at least some Atari archives created
		 * with STZip, as well as archives created by J.H. Holm's ZIPSPLIT 1.1).
		 *----------------------------------------------------------------------- */
		zlseek(fecrec.offset_start_central_directory);
#ifdef OLD_SEEK_TEST
		if (readbuf((char*) & sig, 4) == 0)
		{
			close(fzipfd);
			fzipfd = 0;
			/* RCV added 29-1-99 */
			return PK_ERR;
			/* file may be locked, or possibly disk error(?) */
		}

		if (strncmp(fsig, fcentral_hdr_sig, 4))
#else
			if ((readbuf((char*) & sig, 4) == 0) || sig != CentralFileHeaderSig)
#endif
			{
				if (Verbose < 0)
					Notify(ITRACE, _T("central dir found"));
				fextra_bytes = 0;
				zlseek(fecrec.offset_start_central_directory);
				if ((readbuf((char*) & sig, 4) == 0)
					|| sig != CentralFileHeaderSig)
				{
					DZError(DZ_ERM_NO_CENTRAL);
					delete fUnzInfile;
					fUnzInfile = NULL;

					return PK_BADERR;
				}

				Notify(0, _T("central dir too long"));
				error_in_archive = PK_ERR;
			}

		/* -----------------------------------------------------------------------
		 * Seek to the start of the central directory one last time, since we
		 * have just read the first entry's signature bytes; then list, extract
		 * or test member files as instructed, and close the zipfile.
		 *----------------------------------------------------------------------- */
		if (Verbose < 0)
			Notify(ITRACE, _T("about to extract files (error = %d)"),
			error_in_archive);
		zlseek(fecrec.offset_start_central_directory);
		// GO DO EXTRACT OR TEST
		error = extract_or_test_files();
		/* EXTRACT OR TEST 'EM */

		if (Verbose < 0)
			Notify(ITRACE, _T("Done with extract/list files (error = %d)"),
			error);
		if (error > error_in_archive) /* don't overwrite stronger error */
				error_in_archive = error;
		/* with (for example) a warning */
	}
	/* end if (!too_weird_to_continue) */

	delete fUnzInfile;
	fUnzInfile = NULL;

	return error_in_archive;
}
コード例 #5
0
int CJabberProto::FileSendParse(JABBER_SOCKET s, filetransfer *ft, char* buffer, int datalen)
{
	char* p, *q, *t, *eob;
	char* str;
	int num;
	int currentFile;
	int fileId;
	int numRead;

	eob = buffer + datalen;
	p = buffer;
	num = 0;
	while (ft->state == FT_CONNECTING || ft->state == FT_INITIALIZING) {
		for (q = p; q + 1 < eob && (*q != '\r' || *(q + 1) != '\n'); q++);
		if (q + 1 >= eob)
			break;
		if ((str = (char*)mir_alloc(q - p + 1)) == NULL) {
			ft->state = FT_ERROR;
			break;
		}
		strncpy_s(str, q - p, p, _TRUNCATE);
		str[q - p] = '\0';
		debugLogA("FT Got: %s", str);
		if (ft->state == FT_CONNECTING) {
			// looking for "GET filename.ext HTTP/1.1"
			if (!strncmp(str, "GET ", 4)) {
				for (t = str + 4; *t != '\0' && *t != ' '; t++);
				*t = '\0';
				for (t = str + 4; *t != '\0' && *t == '/'; t++);
				ft->httpPath = mir_a2t(t);
				JabberHttpUrlDecode(ft->httpPath);
				ft->state = FT_INITIALIZING;
				debugLogA("Change to FT_INITIALIZING");
			}
		}
		else {	// FT_INITIALIZING
			if (str[0] == '\0') {
				struct _stati64 statbuf;

				mir_free(str);
				num += 2;

				currentFile = ft->std.currentFileNumber;
				TCHAR *t = _tcsrchr(ft->std.ptszFiles[currentFile], '\\');
				if (t != NULL)
					t++;
				else
					t = ft->std.ptszFiles[currentFile];

				if (ft->httpPath == NULL || mir_tstrcmp(ft->httpPath, t)) {
					if (ft->httpPath == NULL)
						debugLogA("Requested file name does not matched (httpPath == NULL)");
					else
						debugLog(_T("Requested file name does not matched ('%s' vs. '%s')"), ft->httpPath, t);
					ft->state = FT_ERROR;
					break;
				}
				debugLog(_T("Sending [%s]"), ft->std.ptszFiles[currentFile]);
				_tstati64(ft->std.ptszFiles[currentFile], &statbuf);	// file size in statbuf.st_size
				if ((fileId = _topen(ft->std.ptszFiles[currentFile], _O_BINARY | _O_RDONLY)) < 0) {
					debugLogA("File cannot be opened");
					ft->state = FT_ERROR;
					mir_free(ft->httpPath);
					ft->httpPath = NULL;
					break;
				}

				char fileBuffer[2048];
				int bytes = mir_snprintf(fileBuffer, _countof(fileBuffer), "HTTP/1.1 200 OK\r\nContent-Length: %I64u\r\n\r\n", statbuf.st_size);
				WsSend(s, fileBuffer, bytes, MSG_DUMPASTEXT);

				ft->std.flags |= PFTS_SENDING;
				ft->std.currentFileProgress = 0;
				debugLogA("Sending file data...");

				while ((numRead = _read(fileId, fileBuffer, 2048)) > 0) {
					if (Netlib_Send(s, fileBuffer, numRead, 0) != numRead) {
						ft->state = FT_ERROR;
						break;
					}
					ft->std.currentFileProgress += numRead;
					ft->std.totalProgress += numRead;
					ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std);
				}
				_close(fileId);
				if (ft->state != FT_ERROR)
					ft->state = FT_DONE;
				debugLogA("Finishing this file...");
				mir_free(ft->httpPath);
				ft->httpPath = NULL;
				break;
		}	}

		mir_free(str);
		q += 2;
		num += (q-p);
		p = q;
	}

	return num;
}
コード例 #6
0
ファイル: file.c プロジェクト: forostm/libecw
/*
** Get the size of the given file
*/
INT64 NCSFileSizeBytes(NCSTChar *pFilename)
{
#ifdef WIN32
#ifdef _WIN32_WCE
	DWORD dwLow;
	DWORD dwHigh;
	HANDLE hFile;

	if(hFile = CreateFile(pFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL)) {
		dwLow = GetFileSize(hFile, &dwHigh);
		
		if(dwLow == 0xffffffff && GetLastError() != NO_ERROR) {
			CloseHandle(hFile);
			return(-1);
		} else {
			CloseHandle(hFile);
			return((UINT64)dwLow | ((UINT64)dwHigh << 32));
		}
	} else {
		return(-1);
	}

#else	/* _WIN32_WCE */
	struct _stati64 statbuf;
#ifdef NCS_BUILD_UNICODE
#define _tstati64 _wstati64
#else
#define _tstati64 _stati64
#endif

    if(_tstati64(pFilename, &statbuf) != 0) {
		DWORD dwLow;
		DWORD dwHigh;
		HANDLE hFile;

#ifdef NCS_BUILD_UNICODE
		if(hFile = CreateFileW(pFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL)) {
#else
		if(hFile = CreateFileA(pFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL)) {
#endif
			dwLow = GetFileSize(hFile, &dwHigh);
			
			if(dwLow == 0xffffffff && GetLastError() != NO_ERROR) {
				CloseHandle(hFile);
				return(-1);
			} else {
				CloseHandle(hFile);
				return((UINT64)dwLow | ((UINT64)dwHigh << 32));
			}
		} else {
			return(-1);
		}
    }
    return((INT64)statbuf.st_size);
#undef _tstati64
#endif

#elif defined POSIX

#ifdef _LARGEFILE64_SOURCE
    struct stat64 statbuf;

    if (stat64(CHAR_STRING(pFilename), &statbuf) != 0) {
        return(-1); 
    }
    return((INT64)statbuf.st_size);
#else
    struct stat statbuf;

    if (stat(CHAR_STRING(pFilename), &statbuf) != 0) {
        return(-1); 
    }
    return((INT64)statbuf.st_size);
#endif


#elif defined IRIX

	struct stat64 statbuf;

    if (stat(CHAR_STRING(pFilename), &statbuf) != 0) {
        return(-1);
    }
	return((INT64)statbuf.st_size);

#elif defined PALM
	
	NCS_FILE_HANDLE hFile;
	
	if(NCSFileOpen(pFilename, NCS_FILE_READ, &hFile) == NCS_SUCCESS) {
		INT32 nFileSize = hFile->nDBSize;
		
		NCSFileClose(hFile);
		return((INT64)nFileSize);
	}
	return(-1);

#else	/* WIN32 */
#error 	NCSFileSizeBytes();
#endif	/* WIN32 */
}

/*
** Get the size of the given file
*/
INT64 NCSFreeDiskSpaceBytes(char *pDirName, INT64 *pTotal)
{
#ifdef WIN32
	NCS_FUNCADDR pGetDiskFreeSpaceEx;
	//WINBASEAPI BOOL (WINAPI *pGetDiskFreeSpaceEx)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);

	char szPath[MAX_PATH];

	strcpy(szPath, pDirName);
	if(szPath[0] == '\\' && szPath[strlen(szPath) - 1] != '\\') {
		// UNC dir must have trailing backslash
		strcat(szPath, "\\");
	}

	pGetDiskFreeSpaceEx = (NCS_FUNCADDR)GetProcAddress( GetModuleHandle(NCS_T("kernel32.dll")),
							"GetDiskFreeSpaceExA");

	if(pGetDiskFreeSpaceEx) {
		ULARGE_INTEGER i64FreeBytesToCaller;
		ULARGE_INTEGER i64TotalBytes;
		ULARGE_INTEGER i64FreeBytes;

		if(((BOOL (WINAPI *)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER))pGetDiskFreeSpaceEx)(szPath,
					(PULARGE_INTEGER)&i64FreeBytesToCaller,
					(PULARGE_INTEGER)&i64TotalBytes,
					(PULARGE_INTEGER)&i64FreeBytes)) {
			
			if(pTotal) {
				*pTotal = (INT64)i64TotalBytes.QuadPart;
			}
			return((INT64)i64FreeBytesToCaller.QuadPart);
		} else {
			return(-1);
		}
	} else {
#if !defined(_WIN32_WCE)
		DWORD dwSectPerClust;
		DWORD dwBytesPerSect;
		DWORD dwFreeClusters;
		DWORD dwTotalClusters;

		if(GetDiskFreeSpace(OS_STRING(szPath), 
							&dwSectPerClust, 
							&dwBytesPerSect,
							&dwFreeClusters, 
							&dwTotalClusters)) {
			if(pTotal) {
				*pTotal = (INT64)dwBytesPerSect * (INT64)dwSectPerClust * (INT64)dwTotalClusters;
			}
			return((INT64)dwBytesPerSect * (INT64)dwSectPerClust * (INT64)dwFreeClusters);
		} else {
			return(-1);
		}
#elif defined(_WIN32_WCE)
		ULARGE_INTEGER nFreeBytesToCaller;
		ULARGE_INTEGER nTotalBytes;
		ULARGE_INTEGER nTotalFreeBytes;

		if (GetDiskFreeSpaceEx(OS_STRING(szPath), &nFreeBytesToCaller, &nTotalBytes, &nTotalFreeBytes)) {
			if(pTotal) {
				*pTotal = (INT64) nFreeBytesToCaller.QuadPart;
			}
			return((INT64)nFreeBytesToCaller.QuadPart);
		} else {
			return (-1);
		}
#endif
	}
#else // WIN32
	return(-1);
#endif
}
コード例 #7
0
ファイル: setting.cpp プロジェクト: byplayer/yamy
/*
  _UNICODE: read file (UTF-16 LE/BE, UTF-8, locale specific multibyte encoding)
  _MBCS: read file
*/
bool readFile(tstring *o_data, const tstringi &i_filename)
{
	// get size of file
#if 0
	// bcc's _wstat cannot obtain file size
	struct _stat sbuf;
	if (_tstat(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0)
		return false;
#else
	// so, we use _wstati64 for bcc
	struct stati64_t sbuf;
	if (_tstati64(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0)
		return false;
	// following check is needed to cast sbuf.st_size to size_t safely
	// this cast occurs because of above workaround for bcc
	if (sbuf.st_size > UINT_MAX)
		return false;
#endif

	// open
	FILE *fp = _tfopen(i_filename.c_str(), _T("rb"));
	if (!fp)
		return false;

	// read file
	Array<BYTE> buf(static_cast<size_t>(sbuf.st_size) + 1);
	if (fread(buf.get(), static_cast<size_t>(sbuf.st_size), 1, fp) != 1) {
		fclose(fp);
		return false;
	}
	buf.get()[sbuf.st_size] = 0;			// mbstowcs() requires null
	// terminated string

#ifdef _UNICODE
	//
	if (buf.get()[0] == 0xffU && buf.get()[1] == 0xfeU &&
			sbuf.st_size % 2 == 0)
		// UTF-16 Little Endien
	{
		size_t size = static_cast<size_t>(sbuf.st_size) / 2;
		o_data->resize(size);
		BYTE *p = buf.get();
		for (size_t i = 0; i < size; ++ i) {
			wchar_t c = static_cast<wchar_t>(*p ++);
			c |= static_cast<wchar_t>(*p ++) << 8;
			(*o_data)[i] = c;
		}
		fclose(fp);
		return true;
	}

	//
	if (buf.get()[0] == 0xfeU && buf.get()[1] == 0xffU &&
			sbuf.st_size % 2 == 0)
		// UTF-16 Big Endien
	{
		size_t size = static_cast<size_t>(sbuf.st_size) / 2;
		o_data->resize(size);
		BYTE *p = buf.get();
		for (size_t i = 0; i < size; ++ i) {
			wchar_t c = static_cast<wchar_t>(*p ++) << 8;
			c |= static_cast<wchar_t>(*p ++);
			(*o_data)[i] = c;
		}
		fclose(fp);
		return true;
	}

	// try multibyte charset
	size_t wsize = mbstowcs(NULL, reinterpret_cast<char *>(buf.get()), 0);
	if (wsize != size_t(-1)) {
		Array<wchar_t> wbuf(wsize);
		mbstowcs(wbuf.get(), reinterpret_cast<char *>(buf.get()), wsize);
		o_data->assign(wbuf.get(), wbuf.get() + wsize);
		fclose(fp);
		return true;
	}

	// try UTF-8
	{
		Array<wchar_t> wbuf(static_cast<size_t>(sbuf.st_size));
		BYTE *f = buf.get();
		BYTE *end = buf.get() + sbuf.st_size;
		wchar_t *d = wbuf.get();
		enum { STATE_1, STATE_2of2, STATE_2of3, STATE_3of3 } state = STATE_1;

		while (f != end) {
			switch (state) {
			case STATE_1:
				if (!(*f & 0x80))			// 0xxxxxxx: 00-7F
					*d++ = static_cast<wchar_t>(*f++);
				else if ((*f & 0xe0) == 0xc0) {	// 110xxxxx 10xxxxxx: 0080-07FF
					*d = ((static_cast<wchar_t>(*f++) & 0x1f) << 6);
					state = STATE_2of2;
				} else if ((*f & 0xf0) == 0xe0)		// 1110xxxx 10xxxxxx 10xxxxxx:
					// 0800 - FFFF
				{
					*d = ((static_cast<wchar_t>(*f++) & 0x0f) << 12);
					state = STATE_2of3;
				} else
					goto not_UTF_8;
				break;

			case STATE_2of2:
			case STATE_3of3:
				if ((*f & 0xc0) != 0x80)
					goto not_UTF_8;
				*d++ |= (static_cast<wchar_t>(*f++) & 0x3f);
				state = STATE_1;
				break;

			case STATE_2of3:
				if ((*f & 0xc0) != 0x80)
					goto not_UTF_8;
				*d |= ((static_cast<wchar_t>(*f++) & 0x3f) << 6);
				state = STATE_3of3;
				break;
			}
		}
		o_data->assign(wbuf.get(), d);
		fclose(fp);
		return true;

not_UTF_8:
		;
	}
#endif // _UNICODE

	// assume ascii
	o_data->resize(static_cast<size_t>(sbuf.st_size));
	for (off_t i = 0; i < sbuf.st_size; ++ i)
		(*o_data)[i] = buf.get()[i];
	fclose(fp);
	return true;
}
コード例 #8
0
ファイル: msn_proto.cpp プロジェクト: Seldom/miranda-ng
// MsnFileResume - renames a file
int __cdecl CMsnProto::FileResume(HANDLE hTransfer, int* action, const TCHAR** szFilename)
{
	filetransfer* ft = (filetransfer*)hTransfer;

	if (ft->tType == SERVER_HTTP) {
		switch (*action) {
			case FILERESUME_SKIP:
				ft->close();
				ft->bCanceled = true;
				break;
			case FILERESUME_RENAME:
				replaceStrT(ft->std.tszCurrentFile, *szFilename);
				break;
			case FILERESUME_OVERWRITE:
				ft->std.currentFileProgress = 0;
				break;
			case FILERESUME_RESUME:
				{
					struct _stati64 statbuf;
					_tstati64(ft->std.tszCurrentFile, &statbuf);
					ft->std.currentFileProgress = statbuf.st_size;
				}
				break;
		}
		SetEvent(ft->hResumeEvt);
	}
#ifdef OBSOLETE
	else {
		if (!msnLoggedIn || !p2p_sessionRegistered(ft))
			return 1;

		switch (*action) {
		case FILERESUME_SKIP:
			if (ft->p2p_appID != 0)
				p2p_sendStatus(ft, 603);
			else
				msnftp_sendAcceptReject(ft, false);
			break;

		case FILERESUME_RENAME:
			replaceStrT(ft->std.tszCurrentFile, *szFilename);

		default:
			bool fcrt = ft->create() != -1;
			if (ft->p2p_appID != 0) {
				if (fcrt)
					p2p_sendFeedStart(ft);

				p2p_sendStatus(ft, fcrt ? 200 : 603);
			}
			else
				msnftp_sendAcceptReject(ft, fcrt);

			ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_INITIALISING, ft, 0);
			break;
		}
	}
#endif

	return 0;
}
コード例 #9
0
ファイル: ZipFIO.cpp プロジェクト: geoffsmith82/delphizip
int ZipFunc::replaceOrig(const DZStrW &d, const DZStrW& s)
{
    struct stati64 t;        // results of stat()
    int         copy = 0;
    int         d_exists;

	d_exists = _tstati64(d, &t) == 0;
	if (d_exists)
	{
		// respect existing soft and hard links!
		if (t.st_nlink > 1)
			copy = 1;
        else
        {
            if (_tunlink(d))
                return DZ_ERM_ERROR_CREATE;      // Can't erase zip file--give up
            Sleep(5);
        }
    }
    if (!copy)
    {
            // Just move s on top of d
        if (_trename(s, d))// !MoveFile(s, d))
        {
            if (Verbose < 0)
                Notify(IERROR, _T(" replace failed %s (%s)"), s, errno);
            copy = 1;                   // failed ?
            if (errno != ENOTSAM)
				return DZ_ERM_ERROR_CREATE;
        }
    }

    if (copy)
    {
        HANDLE  f,
        g;                    // source and destination files
        int     r;                    // temporary variable
        diag(_T("in replace - open for read"));

        if ((f = CreateFile(s, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL)) <= 0)
        {
            diag(_T("in replace - bad open for Read"));
            Notify(0, _T(" replace: can't open %s [%s]"), s, SysMsg());

			return DZ_ERM_TEMP_FAILED;
        }

        diag(_T("in replace - fopen for write"));

        if ((g = CreateFile(d, GENERIC_WRITE, 0, NULL, CREATE_NEW,
                            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL)) <= 0)
        {
            Close_Handle(&f);
            diag(_T("in replace - bad open for Write"));
			return DZ_ERM_ERROR_CREATE;
        }

        r = filecopy(f, g);

        Close_Handle(&f);
        if (!Close_Handle(&g) || r != DZ_ERR_GOOD)
        {
            DeleteFile(d);
            return r ? (DZ_ERR(r) == DZ_ERR_TEMP_FAILED ? DZ_ERR_ERROR_WRITE : r) : DZ_ERM_ERROR_WRITE;
        }

        DeleteFile(s);
    }

    return DZ_ERR_GOOD;
}
コード例 #10
0
ファイル: proto.cpp プロジェクト: martok/miranda-ng
HANDLE __cdecl CAimProto::SendFile(MCONTACT hContact, const PROTOCHAR* szDescription, PROTOCHAR** ppszFiles)
{
	if (state != 1) return 0;

	if (hContact && szDescription && ppszFiles)
	{
		DBVARIANT dbv;
		if (!getString(hContact, AIM_KEY_SN, &dbv))
		{
			file_transfer *ft = new file_transfer(hContact, dbv.pszVal, NULL);

			bool isDir = false;
			int count = 0;
			while (ppszFiles[count] != NULL)
			{
				struct _stati64 statbuf;
				if (_tstati64(ppszFiles[count++], &statbuf) == 0)
				{
					if (statbuf.st_mode & _S_IFDIR)
					{
						if (ft->pfts.totalFiles == 0) isDir = true;
					}
					else
					{
						ft->pfts.totalBytes += statbuf.st_size;
						++ft->pfts.totalFiles;
					}
				}
			}

			if (ft->pfts.totalFiles == 0)
			{
				delete ft;
				return NULL;
			}

			ft->pfts.flags |= PFTS_SENDING;
			ft->pfts.ptszFiles = ppszFiles;

			ft->file = ft->pfts.totalFiles == 1 || isDir ? mir_utf8encodeT(ppszFiles[0]) : (char*)mir_calloc(1);
			ft->sending = true;
			ft->message = szDescription[0] ? mir_utf8encodeT(szDescription) : NULL;
			ft->me_force_proxy = getByte(AIM_KEY_FP, 0) != 0;
			ft->requester = true;

			ft_list.insert(ft);

			if (ft->me_force_proxy)
			{
				debugLogA("We are forcing a proxy file transfer.");
				ForkThread(&CAimProto::accept_file_thread, ft);
			}
			else
			{
				ft->listen(this);
				aim_send_file(hServerConn, seqno, detected_ip, ft->local_port, false, ft);
			}

			db_free(&dbv);

			return ft;
		}
	}

	return NULL;
}
コード例 #11
0
/** 
 * @brief Shows file/folder selection dialog.
 *
 * We need this custom function so we can select files and folders with the
 * same dialog.
 * - If existing filename is selected return it
 * - If filename in (CFileDialog) editbox and current folder doesn't form
 * a valid path to file, return current folder.
 * @param [in] parent Handle to parent window. Can be a NULL, but then
 *     CMainFrame is used which can cause modality problems.
 * @param [out] path Selected folder/filename
 * @param [in] initialPath Initial file or folder shown/selected.
 * @return TRUE if user choosed a file/folder, FALSE if user canceled dialog.
 */
BOOL SelectFileOrFolder(HWND parent, CString& path, LPCTSTR initialPath /*=NULL*/)
{
	String title = theApp.LoadString(IDS_OPEN_TITLE);

	// This will tell common file dialog what to show
	// and also this will hold its return value
	CString sSelectedFile;

	// check if specified path is a file
	if (initialPath && initialPath[0])
	{
		// If initial path info includes a file
		// we put the bare filename into sSelectedFile
		// so the common file dialog will start up with that file selected
		if (paths_DoesPathExist(initialPath) == IS_EXISTING_FILE)
		{
			String temp;
			SplitFilename(initialPath, 0, &temp, 0);
			sSelectedFile = temp.c_str();
		}
	}

	if (parent == NULL)
		parent = AfxGetMainWnd()->GetSafeHwnd();

	int filterid = IDS_ALLFILES;

	if (!filterid)
		filterid = IDS_ALLFILES;

	String filters = theApp.LoadString(filterid);

	// Convert extension mask from MFC style separators ('|')
	//  to Win32 style separators ('\0')
	LPTSTR filtersStr = &*filters.begin();
	ConvertFilter(filtersStr);

	String dirSelTag = theApp.LoadString(IDS_DIRSEL_TAG);

	// Set initial filename to folder selection tag
	dirSelTag += _T("."); // Treat it as filename
	sSelectedFile = dirSelTag.c_str(); // What is assignment above good for?

	OPENFILENAME_NT4 ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = parent;
	ofn.lpstrFilter = filtersStr;
	ofn.lpstrCustomFilter = NULL;
	ofn.nFilterIndex = 1;
	ofn.lpstrFile = sSelectedFile.GetBuffer(MAX_PATH);
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrInitialDir = initialPath;
	ofn.lpstrTitle = title.c_str();
	ofn.lpstrFileTitle = NULL;
	ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_NOTESTFILECREATE;

	BOOL bRetVal = GetOpenFileName((OPENFILENAME *)&ofn);
	// common file dialog populated sSelectedFile variable's buffer
	sSelectedFile.ReleaseBuffer();
	SetCurrentDirectory(env_GetWindowsDirectory().c_str()); // Free handle held by GetOpenFileName

	if (bRetVal)
	{
		path = sSelectedFile;
		struct _stati64 statBuffer;
		int nRetVal = _tstati64(path, &statBuffer);
		if (nRetVal == -1)
		{
			// We have a valid folder name, but propably garbage as a filename.
			// Return folder name
			String folder = GetPathOnly(sSelectedFile);
			path.Format(_T("%s\\"), folder.c_str());
		}
	}
	return bRetVal;
}