void App::run(void) { TCHAR buf[MAX_CMD_SIZE + 1] = {0}; for (;;) { (void)m_vdisk->ExecCommand(_T("prompt")); memset(buf, 0, sizeof(buf)); TCHAR* ret_t = _fgetts(buf, MAX_CMD_SIZE, stdin); if (ret_t == NULL && errno != EINVAL) { assert(0); _tprintf(_T("ÃüÁî¶ÁÈ¡´íÎó\n")); return; } MyString line(buf); line.term(); if (line.startWith(_T("exit"))) return; (void)m_vdisk->ExecCommand(line.c_str()); } }
int CFastStringArray::AddListFromFile(LPCTSTR fname) { FILE* fp; errno_t err = _tfopen_s(&fp, fname, _T("rt")); if(err) return 0; TCHAR buf[4096]; for(;;){ TCHAR* p = _fgetts(buf, 4096, fp); if(!p) break; int len = _tcslen(p); for(int i=0;i<len;i++){ if(p[i]==_T('\n') || p[i]==_T('\r')){ p[i] = _T('\0'); break; } } if(_tcslen(p)) Add(p); } fclose(fp); return m_count-1; }
BOOL CStdioFile::ReadString( CString &rString ) /*********************************************/ { TCHAR szBuff[128]; TCHAR *pchNL = NULL; rString.Empty(); if( feof( m_pStream ) ) { return( FALSE ); } while( pchNL == NULL && !feof( m_pStream ) ) { if( _fgetts( szBuff, 128, m_pStream ) == NULL && !feof( m_pStream ) ) { CFileException::ThrowErrno( errno, m_strFileName ); } pchNL = _tcschr( szBuff, _T('\n') ); if( pchNL != NULL ) { *pchNL = _T('\0'); } rString += szBuff; } return( TRUE ); }
BOOL CStdioFile::ReadString(CString& rString) { ASSERT_VALID(this); rString = &afxChNil; // empty string without deallocating const int nMaxSize = 128; LPTSTR lpsz = rString.GetBuffer(nMaxSize); LPTSTR lpszResult; int nLen = 0; for (;;) { lpszResult = _fgetts(lpsz, nMaxSize+1, m_pStream); rString.ReleaseBuffer(); // handle error/eof case if (lpszResult == NULL && !feof(m_pStream)) { clearerr(m_pStream); AfxThrowFileException(CFileException::generic, _doserrno, m_strFileName); } // if string is read completely or EOF if (lpszResult == NULL || (nLen = lstrlen(lpsz)) < nMaxSize || lpsz[nLen-1] == '\n') break; nLen = rString.GetLength(); lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen; } // remove '\n' from end of string if present lpsz = rString.GetBuffer(0); nLen = rString.GetLength(); if (nLen != 0 && lpsz[nLen-1] == '\n') rString.GetBufferSetLength(nLen-1); return lpszResult != NULL; }
//------------------------------------------------------------------------------ int LoadUserList(HTTPCSTR path) { FILE *userlist; HTTPCHAR *p; HTTPCHAR user[200]; nUsers=0; userlist=_tfopen(path,_T("r")); if (userlist) { while( (!feof(userlist)) ) { memset(user,0,sizeof(user)); _fgetts(user,sizeof(user)/sizeof(HTTPCHAR)-1,userlist); if ( (_tcslen(user)>1) && (user[0]!=_T('#')) ) { p=user+_tcslen(user)-1; while ( (*p==_T('\r') ) || (*p==_T('\n')) || (*p==_T(' ')) ) { p[0]=_T('\0'); --p; } p=_tcschr(user,_T(':')); if (p) { if (!userpass) { userpass = (USERLIST *)malloc(sizeof(USERLIST)); } else userpass=(USERLIST*)realloc(userpass,sizeof(USERLIST)*(nUsers+1)); //memset(&userpass[nUsers],'\0',sizeof(USERLIST)); p[0]=_T('\0'); _tcsncpy(userpass[nUsers].UserName,user,sizeof(userpass[nUsers].UserName)/sizeof(HTTPCHAR)-1); _tcsncpy(userpass[nUsers].Password,p+1,sizeof(userpass[nUsers].Password)/sizeof(HTTPCHAR)-1); nUsers++; } } } fclose(userlist); } return(nUsers); }
BOOL CCustomAutoComplete::LoadList(LPCTSTR pszFileName) { FILE* fp = _tfsopen(pszFileName, _T("rb"), _SH_DENYWR); if (fp == NULL) return FALSE; // verify Unicode byte-order mark 0xFEFF WORD wBOM = fgetwc(fp); if (wBOM != 0xFEFF){ fclose(fp); return FALSE; } TCHAR szItem[256]; while (_fgetts(szItem, ARRSIZE(szItem), fp) != NULL){ CString strItem(szItem); strItem.Trim(_T(" \r\n")); AddItem(strItem, -1); } fclose(fp); return TRUE; }
//REWRITE: this is inefficient. We better read and parse file once bool getConfigValue(TCHAR* basedir, TCHAR* lookupKey, TCHAR* outValue, int buf_size) { TCHAR config[LAUNCHER_MAXPATH] = {0}; TCHAR buffer[LAUNCHER_MAXPATH*2]; TCHAR *value; FILE *fp; *outValue = 0; if (!getFileInPackage(basedir, CONFIG_FILE, config, LAUNCHER_MAXPATH)) { showError(config, _T("Configuration file is not found!")); return false; } //scan file for the key errno_t err = _tfopen_s(&fp, config, _T("r")); if (err) { return false; } while (_fgetts(buffer, LAUNCHER_MAXPATH*2, fp)) { value = _tcschr(buffer, '='); if (value != NULL) { //end key on the '=', value will point to the value string *value = 0; value++; if (!_tcscmp(buffer, lookupKey)) { //found it fclose(fp); strip_endofline(value); _tcscpy_s(outValue, buf_size, value); return true; } } } fclose(fp); return false; }
/** * \brief */ bool DbConfig::LoadFromFolder(const CPath& cfgFileFolder) { SetDefaults(); CPath cfgFile(cfgFileFolder); cfgFile += cPluginCfgFileName; if (!cfgFile.FileExists()) return false; FILE* fp; _tfopen_s(&fp, cfgFile.C_str(), _T("rt")); if (fp == NULL) return false; bool success = true; TCHAR line[8192]; while (_fgetts(line, _countof(line), fp)) { // Comment or empty line if (line[0] == _T('#') || line[0] == _T('\n')) continue; // Strip newline from the end of the line line[_tcslen(line) - 1] = 0; if (!ReadOption(line)) { success = false; SetDefaults(); break; } } fclose(fp); return success; }
bool excel::ReadExcelFile( _lpctstr strFileName, int nTitleLine ) { FILE* fp; if( ( fp = _tfopen( strFileName, _T("r") ) ) == NULL ) { return FALSE; } _tchar buffer[1024]; int nLine = 0; while( !feof( fp ) ) { buffer[0] = 0; _fgetts( buffer, sizeof( buffer ), fp ); if( !AnalyzeLine( buffer, sizeof( buffer ) ) ) { DestoryTable(); return false; } if( nTitleLine == nLine ) { --m_nLineMax; std::vector< _string >& line = m_impl->strTable[m_nLineMax]; for( size_t n = 0; n < line.size(); ++n ) { _string &idx = line[n]; if( !idx.empty() ) { m_impl->ColumnMap[idx] = n; } } // m_impl->strTable.erase( m_impl->strTable.begin() + m_nLineMax ); } ++nLine; } fclose( fp ); return TRUE; }
BOOL CDuiAutoComplete::LoadList(LPCTSTR pszFileName) { FILE* fp = _tfsopen(pszFileName, _T("rb"), _SH_DENYWR); if (fp == NULL) return FALSE; // УÑé Unicode ±àÂë×Ö½ÚÐò mark 0xFEFF WORD wBOM = fgetwc(fp); if (wBOM != 0xFEFF){ fclose(fp); return FALSE; } TCHAR szItem[256]; while (_fgetts(szItem, ARRSIZE(szItem), fp) != NULL){ CDuiString strItem(szItem); strItem.Replace(_T("\r"),_T("")); strItem.Replace(_T("\n"),_T("")); AddItem(strItem, -1); } fclose(fp); return TRUE; }
BOOL CCustomAutoComplete::LoadList(LPCTSTR pcFileName) { #ifdef _UNICODE FILE *fp = _tfsopen(pcFileName, _T("rb"), _SH_DENYWR); #else FILE *fp = _tfsopen(pcFileName, _T("r"), _SH_DENYWR); #endif if (fp == NULL) return FALSE; #ifdef _UNICODE // Verify Unicode byte-order mark 0xFEFF WORD wBOM = fgetwc(fp); // If not UNICODE file, set reading to ASCII mode if (wBOM != 0xFEFF) { _setmode(_fileno(fp), _O_TEXT); fseek(fp, 0, SEEK_SET); } #endif CString strItem; while (_fgetts(strItem.GetBufferSetLength(256), 256, fp) != NULL) { strItem.ReleaseBuffer(); strItem.Trim(_T(" \r\n")); AddItem(strItem, -1); } fclose(fp); return TRUE; }
bool ReplayLogger::ReadLine(TCHAR *buffer) { static FILE *fp = NULL; if (!buffer) { if (fp) { fclose(fp); fp= NULL; } return false; } if (!fp) { if (_tcslen(FileName)>0) { fp = _tfopen(FileName, TEXT("rt")); } } if (fp==NULL) { return false; } if (_fgetts(buffer, 200, fp)==NULL) { buffer[0] = TEXT('\0'); return false; } return true; }
int _tmain(int argc, TCHAR **argv) { HENV lpEnv = NULL; HDBC lpDbc = NULL; HSTMT lpStmt = NULL; TCHAR *pszConnStr; TCHAR szInput[SQL_QUERY_SIZE]; TCHAR *szLoc = NULL; // Allocate an environment if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &lpEnv) == SQL_ERROR) { fprintf(stderr, "Unable to allocate an environment handle\n"); exit(-1); } // Register this as an application that expects 2.x behavior, // you must register something if you use AllocHandle TRYODBC(lpEnv, SQL_HANDLE_ENV, SQLSetEnvAttr(lpEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC2, 0)); // Allocate a connection TRYODBC(lpEnv, SQL_HANDLE_ENV, SQLAllocHandle(SQL_HANDLE_DBC, lpEnv, &lpDbc)); if (argc > 1) { pszConnStr = *++argv; } else { pszConnStr = NULL; } // Connect to the driver. Use the connection string if supplied // on the input, otherwise let the driver manager prompt for input. _tprintf("calling connect\n"); TRYODBC(lpDbc, SQL_HANDLE_DBC, SQLDriverConnect(lpDbc, GetDesktopWindow(), (SQLCHAR*) pszConnStr, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE)); fprintf(stderr, "Connected!\n"); TRYODBC(lpDbc, SQL_HANDLE_DBC, SQLAllocHandle(SQL_HANDLE_STMT, lpDbc, &lpStmt)); printf("Enter SQL commands, type (control)Z to exit\nSQL COMMAND>"); // Loop to get input and execute queries while (_fgetts(szInput, SQL_QUERY_SIZE - 1, stdin)) { // Execute the query if (!(*szInput)) { printf("SQL COMMAND>"); continue; } if ('!' == szInput[0]) { int len = strlen(szInput); szInput[len] = '\0'; if (0 == strcmp("tables", szInput)) { DoTables(lpStmt); } else { _tprintf("unknown command\n"); } } else { szLoc = strstr(szInput, "?"); if (NULL == szLoc) { if (!DoDirect(lpStmt, (SQLCHAR*) szInput)) { goto Exit; } } else { if (!DoPrepared(lpDbc, szInput)) { goto Exit; } } } TRYODBC(lpStmt, SQL_HANDLE_STMT, SQLFreeStmt(lpStmt, SQL_CLOSE)); printf("SQL COMMAND>"); } Exit: // Free ODBC handles and exit if (lpDbc) { SQLDisconnect(lpDbc); SQLFreeConnect(lpDbc); } if (lpEnv) SQLFreeEnv(lpEnv); printf("\nDisconnected."); return 0; }
// Function name : ParseConfigFile // Description : // Return type : void // Argument : LPTSTR filename void ParseConfigFile(LPTSTR filename) { FILE *fin; TCHAR buffer[1024] = TEXT(""); fin = _tfopen(filename, TEXT("r")); if (fin == NULL) { _tprintf(TEXT("Unable to open file: %s\n"), filename); ExitProcess(1); } while (_fgetts(buffer, 1024, fin)) { // Check for the name of the executable if (_tcsnicmp(buffer, TEXT("exe "), 4) == 0) { TCHAR *pChar = &buffer[4]; while (_istspace(*pChar)) pChar++; _tcscpy(g_pszExe, pChar); pChar = &g_pszExe[_tcslen(g_pszExe)-1]; while (_istspace(*pChar) && (pChar >= g_pszExe)) { *pChar = '\0'; pChar--; } } else // Check for program arguments if (_tcsnicmp(buffer, TEXT("args "), 5) == 0) { TCHAR *pChar = &buffer[5]; while (_istspace(*pChar)) pChar++; _tcscpy(g_pszArgs, pChar); pChar = &g_pszArgs[_tcslen(g_pszArgs)-1]; while (_istspace(*pChar) && (pChar >= g_pszArgs)) { *pChar = '\0'; pChar--; } } else // Check for environment variables if (_tcsnicmp(buffer, TEXT("env "), 4) == 0) { TCHAR *pChar = &buffer[4]; while (_istspace(*pChar)) pChar++; _tcscpy(g_pszEnv, pChar); pChar = &g_pszEnv[_tcslen(g_pszEnv)-1]; while (_istspace(*pChar) && (pChar >= g_pszEnv)) { *pChar = '\0'; pChar--; } } else // Check for hosts if (_tcsnicmp(buffer, TEXT("hosts"), 5) == 0) { g_nHosts = 0; g_pHosts = NULL; HostNode *node, dummy; dummy.next = NULL; node = &dummy; while (_fgetts(buffer, 1024, fin)) { node->next = ParseLineIntoHostNode(buffer); if (node->next != NULL) { node = node->next; g_nHosts++; } } g_pHosts = dummy.next; return; } } fclose(fin); }
void StatusMessageList::LoadFile() { StartupStore(TEXT("Loading status file\n")); TCHAR szFile1[MAX_PATH] = TEXT("\0"); FILE *fp=NULL; // Open file from registry GetRegistryString(szRegistryStatusFile, szFile1, MAX_PATH); ExpandLocalPath(szFile1); SetRegistryString(szRegistryStatusFile, TEXT("\0")); if (_tcslen(szFile1)>0) fp = _tfopen(szFile1, TEXT("rt")); // Unable to open file if (fp == NULL) return; // TODO code: Safer sizes, strings etc - use C++ (can scanf restrict length?) TCHAR buffer[2049]; // Buffer for all TCHAR key[2049]; // key from scanf TCHAR value[2049]; // value from scanf int ms; // Found ms for delay const TCHAR **location; // Where to put the data int found; // Entries found from scanf bool some_data; // Did we find some in the last loop... // Init first entry _init_Status(StatusMessageData_Size); some_data = false; /* Read from the file */ while ( (StatusMessageData_Size < MAXSTATUSMESSAGECACHE) && _fgetts(buffer, 2048, fp) && ((found = _stscanf(buffer, TEXT("%[^#=]=%[^\n]\n"), key, value)) != EOF) ) { // Check valid line? If not valid, assume next record (primative, but works ok!) if ((found != 2) || key[0] == 0 || value[0] == 0) { // Global counter (only if the last entry had some data) if (some_data) { StatusMessageData_Size++; some_data = false; _init_Status(StatusMessageData_Size); } } else { location = NULL; if (_tcscmp(key, TEXT("key")) == 0) { some_data = true; // Success, we have a real entry location = &StatusMessageData[StatusMessageData_Size].key; } else if (_tcscmp(key, TEXT("sound")) == 0) { StatusMessageData[StatusMessageData_Size].doSound = true; location = &StatusMessageData[StatusMessageData_Size].sound; } else if (_tcscmp(key, TEXT("delay")) == 0) { if (_stscanf(value, TEXT("%d"), &ms) == 1) StatusMessageData[StatusMessageData_Size].delay_ms = ms; } else if (_tcscmp(key, TEXT("hide")) == 0) { if (_tcscmp(value, TEXT("yes")) == 0) StatusMessageData[StatusMessageData_Size].doStatus = false; } // Do we have somewhere to put this && is it currently empty ? (prevent lost at startup) if (location && (_tcscmp(*location, TEXT("")) == 0)) { // TODO code: this picks up memory lost from no entry, but not duplicates - fix. if (*location) { // JMW fix memory leak free((void*)*location); } *location = StringMallocParse(value); } } } // How many we really got (blank next just in case) StatusMessageData_Size++; _init_Status(StatusMessageData_Size); // file was ok, so save it to registry ContractLocalPath(szFile1); SetRegistryString(szRegistryStatusFile, szFile1); fclose(fp); }
bool CServerListCtrl::StaticServerFileRemove(const CServer *server) { try { if (!server->IsStaticMember()) return true; CString strLine; CString strTest; TCHAR buffer[1024]; int lenBuf = 1024; int pos; CString StaticFilePath = thePrefs.GetConfigDir() + _T("staticservers.dat"); CString StaticTempPath = thePrefs.GetConfigDir() + _T("statictemp.dat"); FILE* staticservers = _tfsopen(StaticFilePath , _T("r"), _SH_DENYWR); FILE* statictemp = _tfsopen(StaticTempPath , _T("w"), _SH_DENYWR); if ((staticservers == NULL) || (statictemp == NULL)) { if (staticservers) fclose(staticservers); if (statictemp) fclose(statictemp); LogError(LOG_STATUSBAR, GetResString(IDS_ERROR_SSF)); return false; } while (!feof(staticservers)) { if (_fgetts(buffer, lenBuf, staticservers) == 0) break; strLine = buffer; // ignore comments or invalid lines if (strLine.GetAt(0) == _T('#') || strLine.GetAt(0) == _T('/')) continue; if (strLine.GetLength() < 5) continue; // Only interested in "host:port" pos = strLine.Find(_T(',')); if (pos == -1) continue; strLine = strLine.Left(pos); // Get host and port from given server strTest.Format(_T("%s:%i"), server->GetAddress(), server->GetPort()); // Compare, if not the same server write original line to temp file if (strLine.Compare(strTest) != 0) _ftprintf(statictemp, buffer); } fclose(staticservers); fclose(statictemp); // All ok, remove the existing file and replace with the new one CFile::Remove( StaticFilePath ); CFile::Rename( StaticTempPath, StaticFilePath ); } catch (...) { ASSERT(0); return false; } return true; }
int _tmain(int argc, LPTSTR argv[]) { TCHAR buf[256]; HANDLE wPipe, rPipe, rrPipe; int comando; int aEsperaDeJogar = 0; BOOL ret; DWORD n; HANDLE hThread; COMANDO_DO_CLIENTE cmd1; COMANDO_DO_SERVIDOR cmd; hMutexEspera = CreateMutex(NULL, TRUE, NULL); #ifdef UNICODE _setmode(_fileno(stdin), _O_WTEXT); _setmode(_fileno(stdout), _O_WTEXT); #endif _tprintf(TEXT("[CLIENTE]Esperar pelo pipe '%s'(WaitNamedPipe)\n"), PIPE_N_WRITE); if (!WaitNamedPipe(PIPE_N_WRITE, NMPWAIT_WAIT_FOREVER)) { _tprintf(TEXT("[ERRO] Ligar ao pipe '%s'... (WaitNamedPipe)\n"), PIPE_N_WRITE); exit(-1); } _tprintf(TEXT("[CLIENTE] Ligação ao SERVIDOR...\n")); wPipe = CreateFile(PIPE_N_WRITE, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //cria ligaçao if (wPipe == NULL) { _tprintf(TEXT("[ERRO] Ligar ao pipe '%s'... (CreateFile)\n"), PIPE_N_WRITE); exit(-1); } _tprintf(TEXT("[CLIENTE] Pipe para escrita estabelecido...\n")); rPipe = CreateFile(PIPE_N_READ, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (rPipe == NULL) { _tprintf(TEXT("[ERRO] Ligar ao pipe '%s'... (CreateFile)\n"), PIPE_N_READ); exit(-1); } _tprintf(TEXT("[CLIENTE] Pipe para leitura estabelecido...\n")); rrPipe = CreateFile(PIPE_N_READT, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (rrPipe == NULL) { _tprintf(TEXT("[ERRO] Ligar ao pipe '%s'... (CreateFile)\n"), PIPE_N_READT); exit(-1); } _tprintf(TEXT("[CLIENTE] Pipe para leitura estabelecido...\n")); //Inicia_comunicacao(); //dll //Invocar a thread que recebe info do servidor hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)RecebeDoServidor, (LPVOID)rrPipe, 0, NULL); if (hThread == NULL) { _tprintf(TEXT("[ERRO] Thread não foi lançada\n")); exit(-1); } _tprintf(TEXT("[CLIENTE]Criei a Thread para receber do servidor...\n")); ret = ReadFile(rPipe, &cmd, sizeof(COMANDO_DO_SERVIDOR), &n, NULL); if (!ret || !n) _tprintf(TEXT("[CLIENTE]Recebi %d bytes\n "), n); if (cmd.resposta == 20) { indice = cmd.jogador.ID; pid = cmd.jogador.pid; _tprintf(TEXT("[CLIENTE[%d]]Recebi o meu ID e o meu pid %d\n "), indice,pid); } while (1) { if (emjogo == 0) { if (fezlogin == 0) { _tprintf(TEXT("0 - login \n 1 - registar\n")); _tprintf(TEXT("[CLIENTE] comando: ")); _fgetts(buf, 256, stdin); comando = _ttoi(buf); if (comando == 0 || comando == 1) { _tprintf(TEXT("Utilizador: ")); _fgetts(buf, 15, stdin); _tcscpy_s(cmd1.user.login, TAM_LOG, buf); // _tprintf(TEXT("o nome foi : %s "), cmd1.user.login); cmd1.tipoComando = comando; cmd1.ID = indice; ret = WriteFile(wPipe, &cmd1, sizeof(COMANDO_DO_CLIENTE), &n, NULL); //manda comando if (!ret || !n) break; ret = ReadFile(rPipe, &cmd, sizeof(COMANDO_DO_SERVIDOR), &n, NULL);//recebe resposta if (!ret || !n) break; _tprintf(TEXT("[CLIENTE]Recebi %d bytes\n "), n); _tprintf(TEXT("msg : %s \n"),cmd.msg); if (cmd.resposta == 1) //entra em jogo { fezlogin = 1; _tprintf(TEXT("[CLIENTE[%d] Fiz login!\n "), indice); } } } else { //escreve e recebe auto para saber se if (aEsperaDeJogar == 0) { _tprintf(TEXT("0 - criar jogo\n 1 - Juntar ao jogo \n 5 - sair\n")); _tprintf(TEXT("[CLIENTE] comando: ")); _fgetts(buf, 256, stdin); comando = _ttoi(buf); if (comando == 0){ //porque la no server o 2 é que cria jogo comando = 2; }else if (comando == 1){ comando = 3; }else if (comando == 5){ comando = 10;} if (comando == 10 || comando == 2 || comando == 3) { cmd1.tipoComando = comando; cmd1.ID = indice; ret = WriteFile(wPipe, &cmd1, sizeof(COMANDO_DO_CLIENTE), &n, NULL); if (!ret || !n) break; ret = ReadFile(rPipe, &cmd, sizeof(COMANDO_DO_SERVIDOR), &n, NULL); if (!ret || !n) break; _tprintf(TEXT("msg : %s \n"), cmd.msg); if (cmd.tipoResposta== 1)//caso receba resposta de um pedido de criar jogo { if (cmd.resposta == 1) { //caso tenha sido o primeiro a criar o jogo vai ficar com um menu de iniciar jogo _tprintf(TEXT("0 - começar\n")); _tprintf(TEXT("[CLIENTE] comando: ")); do { _fgetts(buf, 256, stdin); comando = _ttoi(buf); if (comando == 0) //porque la no server o 4 corresponde a começar o jogo comando = 4; } while (comando != 4); cmd1.tipoComando = comando; cmd1.ID = indice; ret = WriteFile(wPipe, &cmd1, sizeof(COMANDO_DO_CLIENTE), &n, NULL); if (!ret || !n) break; ret = ReadFile(rPipe, &cmd, sizeof(COMANDO_DO_SERVIDOR), &n, NULL); if (!ret || !n) break; aEsperaDeJogar = 1; emjogo = 1; _tprintf(TEXT("msg : %s \n"), cmd.msg); } } else if (cmd.tipoResposta == 2) { if (cmd.resposta == 1) { aEsperaDeJogar = 1; } else if (cmd.resposta == 2) { } } } } else { _tprintf(TEXT("A espera... ")); while (emjogo != 1) { Sleep(500); } } } //fim do else do login } else { _tprintf(TEXT("[CLIENTE] cliente indice [%d] \n"), indice); _tprintf(TEXT("0 - esquerda \n 1 - direita \n 2 - cima \n 3 - baixo\n")); _tprintf(TEXT("[CLIENTE] comando: ")); //ReleaseMutex(hMutexEspera); _fgetts(buf, 256, stdin); comando = _ttoi(buf); if (comando >= 0 && comando <= 3) { if (comando == 0) comando = 5; if (comando == 1) comando = 6; if (comando == 2) comando = 8; if (comando == 3) comando = 7; cmd1.tipoComando = comando; cmd1.ID = indice; ret = WriteFile(wPipe, &cmd1, sizeof(COMANDO_DO_CLIENTE), &n, NULL); if (!ret || !n) break; _tprintf(TEXT("[CLIENTE](ReadFile) enviei %d bytes\n"), n); //ret = ReadFile(rPipe, &cmd, sizeof(COMANDO_DO_SERVIDOR), &n, NULL); //imprimeMundo(cmd); //if (!ret || !n) // break; //_tprintf(TEXT("[CLIENTE](ReadFile) Recebi %d bytes\n "), n); // if (cmd.resposta == 1) // { // _tprintf(TEXT("Jogador[%d] : saude : %d \n lentidao : %d \n x = %d y = %d\n"),cmd.jogador.ID, cmd.jogador.saude, cmd.jogador.lentidao, cmd.jogador.pos.x, cmd.jogador.pos.y); // } } } if (comando == -1) { break; } } //CloseHandle(wPipe); //CloseHandle(rPipe); CloseHandle(hThread); Sleep(200); return 0; }
int CPreviewApps::ReadAllApps() { RemoveAllApps(); CString strFilePath = GetDefaultAppsFile(); FILE* readFile = _tfsopen(strFilePath, _T("r"), _SH_DENYWR); if (readFile != NULL) { CString name, url, sbuffer; while (!feof(readFile)) { TCHAR buffer[1024]; if (_fgetts(buffer, ARRSIZE(buffer), readFile) == NULL) break; sbuffer = buffer; // ignore comments & too short lines if (sbuffer.GetAt(0) == _T('#') || sbuffer.GetAt(0) == _T('/') || sbuffer.GetLength() < 5) continue; int iPos = 0; CString strTitle = sbuffer.Tokenize(_T("="), iPos); strTitle.Trim(); if (!strTitle.IsEmpty()) { CString strCommandLine = sbuffer.Tokenize(_T(";"), iPos); strCommandLine.Trim(); if (!strCommandLine.IsEmpty()) { LPCTSTR pszCommandLine = strCommandLine; LPTSTR pszCommandArgs = PathGetArgs(pszCommandLine); CString strCommand, strCommandArgs; if (pszCommandArgs) strCommand = strCommandLine.Left(pszCommandArgs - pszCommandLine); else strCommand = strCommandLine; strCommand.Trim(_T(" \t\"")); if (!strCommand.IsEmpty()) { UINT uMinCompletedSize = 0; UINT uMinStartOfFile = 0; CStringArray astrExtensions; CString strParams = sbuffer.Tokenize(_T(";"), iPos); while (!strParams.IsEmpty()) { int iPosParam = 0; CString strId = strParams.Tokenize(_T("="), iPosParam); if (!strId.IsEmpty()) { CString strValue = strParams.Tokenize(_T("="), iPosParam); if (strId.CompareNoCase(_T("Ext")) == 0) { if (!strValue.IsEmpty()) { if (strValue[0] != _T('.')) strValue = _T('.') + strValue; astrExtensions.Add(strValue); } } else if (strId.CompareNoCase(_T("MinSize")) == 0) { if (!strValue.IsEmpty()) _stscanf(strValue, _T("%u"), &uMinCompletedSize); } else if (strId.CompareNoCase(_T("MinStart")) == 0) { if (!strValue.IsEmpty()) _stscanf(strValue, _T("%u"), &uMinStartOfFile); } } strParams = sbuffer.Tokenize(_T(";"), iPos); } SPreviewApp svc; svc.strTitle = strTitle; svc.strCommand = strCommand; svc.strCommandArgs = pszCommandArgs; svc.strCommandArgs.Trim(); svc.astrExtensions.Append(astrExtensions); svc.uMinCompletedSize = uMinCompletedSize; svc.uMinStartOfFile = uMinStartOfFile; m_aApps.Add(svc); } } } } fclose(readFile); struct _stat st; if (_tstat(strFilePath, &st) == 0) m_tDefAppsFileLastModified = st.st_mtime; } return m_aApps.GetCount(); }
// Read in the config file for the whole application int ConfigAppLoad() { TCHAR szConfig[MAX_PATH]; TCHAR szLine[1024]; FILE* h; #ifdef _UNICODE setlocale(LC_ALL, ""); #endif CreateConfigName(szConfig); if ((h = _tfopen(szConfig, _T("rt"))) == NULL) { return 1; } // Go through each line of the config file while (_fgetts(szLine, sizeof(szLine), h)) { int nLen = _tcslen(szLine); // Get rid of the linefeed at the end if (szLine[nLen - 1] == 10) { szLine[nLen - 1] = 0; nLen--; } #define VAR(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x)); \ if (szValue) x = _tcstol(szValue, NULL, 0); } #define VAR64(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x)); \ if (szValue) x = (long long)_tcstod(szValue, NULL); } #define FLT(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x)); \ if (szValue) x = _tcstod(szValue, NULL); } #define STR(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x) _T(" ")); \ if (szValue) _tcscpy(x,szValue); } VAR(nIniVersion); // Emulation VAR(bBurnUseASMCPUEmulation); // Video VAR(nVidDepth); VAR(nVidRefresh); VAR(nVidRotationAdjust); // horizontal oriented VAR(nVidHorWidth); VAR(nVidHorHeight); VAR(bVidArcaderesHor); VAR(VidPreset[0].nWidth); VAR(VidPreset[0].nHeight); VAR(VidPreset[1].nWidth); VAR(VidPreset[1].nHeight); VAR(VidPreset[2].nWidth); VAR(VidPreset[2].nHeight); VAR(VidPreset[3].nWidth); VAR(VidPreset[3].nHeight); VAR(nScreenSizeHor); // vertical oriented VAR(nVidVerWidth); VAR(nVidVerHeight); VAR(bVidArcaderesVer); VAR(VidPresetVer[0].nWidth); VAR(VidPresetVer[0].nHeight); VAR(VidPresetVer[1].nWidth); VAR(VidPresetVer[1].nHeight); VAR(VidPresetVer[2].nWidth); VAR(VidPresetVer[2].nHeight); VAR(VidPresetVer[3].nWidth); VAR(VidPresetVer[3].nHeight); VAR(nScreenSizeVer); VAR(nWindowSize); VAR(nWindowPosX); VAR(nWindowPosY); VAR(bDoGamma); VAR(bVidUseHardwareGamma); VAR(bHardwareGammaOnly); FLT(nGamma); VAR(bVidFullStretch); VAR(bVidCorrectAspect); VAR(bVidAutoSwitchFull); VAR(bVidTripleBuffer); VAR(bVidVSync); VAR(bVidScanlines); VAR(nVidScanIntensity); VAR(bMonitorAutoCheck); VAR(nVidScrnAspectX); VAR(nVidScrnAspectY); VAR(bForce60Hz); VAR(bAlwaysDrawFrames); VAR(bVidUsePlaceholder); STR(szPlaceHolder); VAR(nVidSelect); VAR(nVidBlitterOpt[0]); VAR64(nVidBlitterOpt[1]); VAR(nVidBlitterOpt[2]); VAR(nVidBlitterOpt[3]); // DirectDraw blitter VAR(bVidScanHalf); // Direct3D blitter VAR(bVidBilinear); VAR(bVidScanDelay); VAR(bVidScanRotate); VAR(bVidScanBilinear); VAR(nVidFeedbackIntensity); VAR(nVidFeedbackOverSaturation); FLT(fVidScreenAngle); FLT(fVidScreenCurvature); VAR(bVidForce16bit); VAR(nVidTransferMethod); // DirectX Graphics blitter FLT(dVidCubicB); FLT(dVidCubicC); // Sound VAR(nAudSelect); VAR(nAudSegCount); VAR(nInterpolation); VAR(nFMInterpolation); VAR(nAudSampleRate[0]); VAR(nAudDSPModule[0]); VAR(nAudSampleRate[1]); VAR(nAudDSPModule[1]); // Other STR(szLocalisationTemplate); STR(szGamelistLocalisationTemplate); VAR(nVidSDisplayStatus); VAR(nMinChatFontSize); VAR(nMaxChatFontSize); VAR(bModelessMenu); VAR(nSplashTime); VAR(bDrvSaveAll); VAR(nAppThreadPriority); VAR(bAlwaysProcessKeyboardInput); VAR(bAutoPause); VAR(bSaveInputs); VAR(nLoadMenuShowX); VAR(nLoadMenuBoardTypeFilter); VAR(nLoadMenuGenreFilter); VAR(nLoadMenuFamilyFilter); STR(szAppRomPaths[0]); STR(szAppRomPaths[1]); STR(szAppRomPaths[2]); STR(szAppRomPaths[3]); STR(szAppRomPaths[4]); STR(szAppRomPaths[5]); STR(szAppRomPaths[6]); STR(szAppRomPaths[7]); STR(szAppPreviewsPath); STR(szAppTitlesPath); STR(szAppSelectPath); STR(szAppVersusPath); STR(szAppHowtoPath); STR(szAppScoresPath); STR(szAppBossesPath); STR(szAppGameoverPath); STR(szAppFlyersPath); STR(szAppMarqueesPath); STR(szAppControlsPath); STR(szAppCabinetsPath); STR(szAppPCBsPath); STR(szAppCheatsPath); STR(szAppHistoryPath); STR(szAppListsPath); STR(szAppDatListsPath); STR(szAppIpsPath); STR(szAppIconsPath); STR(szAppArchivesPath); STR(szAppHiscorePath); VAR(nMenuUITheme); VAR(bNoChangeNumLock); VAR(bSaveCRoms); VAR(EnableHiscores); VAR(nSelectedLanguage); VAR(bEnableIcons); VAR(nIconsSize); STR(szPrevGames[0]); STR(szPrevGames[1]); STR(szPrevGames[2]); STR(szPrevGames[3]); STR(szPrevGames[4]); STR(szPrevGames[5]); STR(szPrevGames[6]); STR(szPrevGames[7]); STR(szPrevGames[8]); STR(szPrevGames[9]); // Default Controls VAR(nPlayerDefaultControls[0]); STR(szPlayerDefaultIni[0]); VAR(nPlayerDefaultControls[1]); STR(szPlayerDefaultIni[1]); VAR(nPlayerDefaultControls[2]); STR(szPlayerDefaultIni[2]); VAR(nPlayerDefaultControls[3]); STR(szPlayerDefaultIni[3]); #undef STR #undef FLT #undef VAR #undef VAR64 } fclose(h); return 0; }
// A helper function that creates a error report for testing BOOL TestUtils::CreateErrorReport(CString sTmpFolder, CString& sErrorReportName, CString& sMD5Hash) { BOOL bStatus = FALSE; CString sReportFolder; DWORD dwExitCode = 1; WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; CString sSearchPattern = sTmpFolder + "\\*.zip"; CString sMD5FileName; FILE* f = NULL; TCHAR szHashBuff[256] = _T(""); HKEY hKey = NULL; LONG lResult = -1; CString sKeyName = _T("Software\\CrashRpt&ၸwer\\应用程序名称"); CString sKeyName2 = _T("HKEY_CURRENT_USER\\") + sKeyName; lResult = RegCreateKey(HKEY_CURRENT_USER, sKeyName, &hKey); if(lResult!=ERROR_SUCCESS) goto cleanup; DWORD dwVal = 12345; lResult = RegSetValueEx(hKey, _T("Value$%^!@#&123fer"), 0, REG_DWORD, (LPBYTE)&dwVal, sizeof(DWORD)); if(lResult!=ERROR_SUCCESS) goto cleanup; CR_INSTALL_INFOW infoW; memset(&infoW, 0, sizeof(CR_INSTALL_INFOW)); infoW.cb = sizeof(CR_INSTALL_INFOW); infoW.pszAppName = L"My& app Name &"; // Use appname with restricted XML characters infoW.pszAppVersion = L"1.0.0 &<'a应> \"<"; infoW.pszErrorReportSaveDir = sTmpFolder; infoW.dwFlags = CR_INST_NO_GUI|CR_INST_DONT_SEND_REPORT|CR_INST_STORE_ZIP_ARCHIVES; int nInstallResult = crInstallW(&infoW); if(nInstallResult!=0) goto cleanup; crAddScreenshot(CR_AS_MAIN_WINDOW); crAddPropertyW(L"CustomProp", L"Property Value"); crAddRegKey(sKeyName2, L"regkey.xml", 0); CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(ei); ei.exctype = CR_SEH_EXCEPTION; ei.code = 0x123; // Generate error report int nGenResult = crGenerateErrorReport(&ei); if(nGenResult!=0) goto cleanup; // Wait until CrashSender process exits WaitForSingleObject(ei.hSenderProcess, INFINITE); // Check exit code GetExitCodeProcess(ei.hSenderProcess, &dwExitCode); if(dwExitCode!=0) goto cleanup; // Get ZIP name hFind = FindFirstFile(sSearchPattern, &ffd); if(hFind==INVALID_HANDLE_VALUE) goto cleanup; sErrorReportName = sTmpFolder + _T("\\") + CString(ffd.cFileName); FindClose(hFind); hFind = NULL; // Get MD5 name sSearchPattern = sTmpFolder + "\\*.md5"; hFind = FindFirstFile(sSearchPattern, &ffd); if(hFind==INVALID_HANDLE_VALUE) goto cleanup; sMD5FileName = sTmpFolder + _T("\\") + CString(ffd.cFileName); #if _MSC_VER < 1400 f = _tfopen(sMD5FileName, _T("rt")); #else _tfopen_s(&f, sMD5FileName, _T("rt")); #endif if(f==NULL) goto cleanup; TCHAR* szHash = _fgetts(szHashBuff, 256, f); if(szHash==NULL) goto cleanup; sMD5Hash = szHash; if(sMD5Hash.GetLength()!=32) goto cleanup; // Hash must be 32 characters in length bStatus = TRUE; cleanup: crUninstall(); if(f!=NULL) fclose(f); if(hFind!=INVALID_HANDLE_VALUE) FindClose(hFind); if(hKey) RegCloseKey(hKey); RegDeleteKey(HKEY_CURRENT_USER, sKeyName); return bStatus; }
// Read in the config file for the game-specific inputs int ConfigGameLoad(bool bOverWrite) { TCHAR szLine[256]; int nFileVersion = 0; FILE* h = _tfopen(GameConfigName(), _T("rt")); if (h == NULL) { return 1; } if (bOverWrite) { nAnalogSpeed = 0x0100; nBurnCPUSpeedAdjust = 0x0100; } // Go through each line of the config file and process inputs while (_fgetts(szLine, sizeof(szLine), h)) { TCHAR *szValue; int nLen = _tcslen(szLine); // Get rid of the linefeed at the end if (szLine[nLen - 1] == 10) { szLine[nLen - 1] = 0; nLen--; } szValue = LabelCheck(szLine, _T("version")); if (szValue) { nFileVersion = _tcstol(szValue, NULL, 0); } if (bOverWrite) { szValue = LabelCheck(szLine, _T("analog")); if (szValue) { nAnalogSpeed = _tcstol(szValue, NULL, 0); } szValue = LabelCheck(szLine, _T("cpu")); if (szValue) { nBurnCPUSpeedAdjust = _tcstol(szValue, NULL, 0); } } if (nConfigMinVersion <= nFileVersion && nFileVersion <= nBurnVer) { szValue = LabelCheck(szLine, _T("input")); if (szValue) { GameInpRead(szValue, bOverWrite); continue; } szValue = LabelCheck(szLine, _T("macro")); if (szValue) { GameInpMacroRead(szValue, bOverWrite); continue; } szValue = LabelCheck(szLine, _T("custom")); if (szValue) { GameInpCustomRead(szValue, bOverWrite); continue; } } } fclose(h); return 0; }
// Favorite Game List parsing module int ParseFavListDat() { FILE *fp = _tfopen(_T("config\\favorites.dat"), _T("r")); // not 'rb' anymore, there's no need if(!fp) return 1; // failed to open file int x = 0; int nLineNum = 0; TCHAR szLine[1000]; TCHAR* pch = NULL; TCHAR* str = NULL; TCHAR* pszDrvName = NULL; TCHAR* pszPlayCounter = NULL; while (1) { if (!_fgetts(szLine, 1000, fp)) break; // If there are no more lines, break loop if (!_tcsncmp (_T("[Favorites]"), szLine, 11)) continue; // Not parsing '[Favorites]' line, so continue with the other lines // Split the current line to send each value to the proper string variables str = szLine; pch = _tcstok(str, _T(";")); while(pch != NULL) { if(x == 0) pszDrvName = pch; // Driver name (Ex. mvsc) if(x == 1) pszPlayCounter = pch; // Play Counter pch = _tcstok(NULL, _T(";")); x++; } x = 0; // reset this to zero for next line // Get the favorite game info from FBA itself not from text strings, this is the proper way // --------------------------------------------------------------------------------------------------------- int nBurnDrvSelectOld = nBurnDrvSelect; for (unsigned int nDrvCheck = 0; nDrvCheck < nBurnDrvCount; nDrvCheck++) { nBurnDrvSelect = nDrvCheck; if (!_tcscmp(BurnDrvGetText(DRV_NAME), pszDrvName)) break; } FavDrvSetContent(FAV_DRV_NAME, nLineNum, BurnDrvGetText(DRV_NAME), -2); #if defined (_UNICODE) FavDrvSetContent(FAV_DRV_TITLE, nLineNum, BurnDrvGetText(DRV_FULLNAME), -2); // Unicode Game Title #else FavDrvSetContent(FAV_DRV_TITLE, nLineNum, BurnDrvGetText(DRV_ASCIIONLY | DRV_FULLNAME), -2); // ASCII Game Title #endif FavDrvSetContent(FAV_DRV_HARDWARE, nLineNum, BurnDrvGetText(DRV_SYSTEM), -2); FavDrvSetContent(FAV_DRV_YEAR, nLineNum, BurnDrvGetText(DRV_DATE), -2); FavDrvSetContent(FAV_DRV_COMPANY, nLineNum, BurnDrvGetText(DRV_MANUFACTURER), -2); FavDrvSetContent(FAV_DRV_MAXPLAYERS, nLineNum, NULL, BurnDrvGetMaxPlayers()); FavDrvSetContent(FAV_DRV_PLAYCOUNTER, nLineNum, pszPlayCounter, -2); FavDrvSetContent(FAV_DRV_NUMBER, nLineNum, NULL, nBurnDrvSelect); nBurnDrvSelect = nBurnDrvSelectOld; // --------------------------------------------------------------------------------------------------------- nLineNum++; // next line } nFavDrvCount = nLineNum; fclose(fp); return 1; }
BOOL ECP_GetClipbook(LPCTSTR pszFileName, PECPCLIPBOOK pClipbook) { FILE *fEcpFile; TCHAR szLine[ECP_MAX_LINE]; LPTSTR pszLine; if ((fEcpFile = fopen(pszFileName, _T("r"))) == NULL) goto ErrReturn; _tcscpy(pClipbook->szFileName, pszFileName); while (!feof(fEcpFile)) { int i; _fgetts(szLine, ECP_MAX_LINE, fEcpFile); pszLine = szLine; String_TrimLeft(pszLine, -1); String_TrimRight(pszLine, _T('\n')); String_TrimRight(pszLine, -1); if (pszLine[0] == _T('#')) // Comment continue; for (i = 0; i < CBFUNC_COUNT; i++) { if (String_NumEqual(pszLine, cbFunctions[i].szName, _tcslen(cbFunctions[i].szName), TRUE)) { pszLine += _tcslen(cbFunctions[i].szName); if (pszLine[0] != _T('=')) { MessageBox(g_hwndMain, _T("Error while parsing Clipbook. Missing ="), _T("Clipbook Error"), MB_OK); goto ErrReturn; } pszLine++; switch (cbFunctions[i].eType) { case CBTITLE: ECP_GetString(&pClipbook->pszTitle, pszLine, FALSE); break; case CBSORT: if (!ECP_GetBoolean(&pClipbook->bSort, pszLine)) goto ErrReturn; break; case CBTCLENABLE: if (!ECP_GetBoolean(&pClipbook->bTclFile, pszLine)) goto ErrReturn; break; } break; // out of the inner for () } } } fclose(fEcpFile); return (TRUE); ErrReturn: pClipbook = NULL; if (fEcpFile != NULL) fclose(fEcpFile); return (FALSE); }
int _tmain (int argc, LPTSTR argv []) { BOOL exitFlag = FALSE; TCHAR command [MAX_COMMAND_LINE+10], *pc; DWORD i, locArgc; /* Local argc */ TCHAR argstr [MAX_ARG] [MAX_COMMAND_LINE]; LPTSTR pArgs [MAX_ARG]; if (!WindowsVersionOK (3, 1)) ReportError (_T("This program requires Windows NT 3.1 or greater"), 1, FALSE); debug = (argc > 1); /* simple debug flag */ /* Prepare the local "argv" array as pointers to strings */ for (i = 0; i < MAX_ARG; i++) pArgs[i] = argstr[i]; /* Open the SC Control Manager on the local machine, with the default database, and all access. */ hScm = OpenSCManager (NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS); if (hScm == NULL) ReportError (_T("Cannot open SC Manager"), 1, TRUE); /* Main command proceesing loop */ _tprintf (_T("\nWindows Service Management")); while (!exitFlag) { _tprintf (_T("\nSM$")); _fgetts (command, MAX_COMMAND_LINE, stdin); /* Replace the new line character with a string end. */ pc = _tcschr (command, _T('\n')); *pc = _T('\0'); if (debug) _tprintf (_T("%s\n"), command); /* Convert the command to "argc, argv" form. */ GetArgs (command, &locArgc, pArgs); CharLower (argstr [0]); /* The command is case-insensitive */ if (debug) _tprintf (_T("\n%s %s %s %s"), argstr[0], argstr[1], argstr[2], argstr[3]); if (_tcscmp (argstr[0], _T("create")) == 0) { Create (locArgc, pArgs, command); } else if (_tcscmp (argstr[0], _T("delete")) == 0) { Delete (locArgc, pArgs, command); } else if (_tcscmp (argstr[0], _T("start")) == 0) { Start (locArgc, pArgs, command); } else if (_tcscmp (argstr[0], _T("control")) == 0) { Control (locArgc, pArgs, command); } else if (_tcscmp (argstr[0], _T("quit")) == 0) { exitFlag = TRUE; } else _tprintf (_T("\nCommand not recognized")); } CloseServiceHandle (hScm); return 0; }
static int FBALocaliseParseFile(TCHAR* pszFilename) { LocaliseResourceInfo CurrentResource; wchar_t wszBuffer[5120]; int nTemplateVersion = 0; wchar_t szLine[5120]; wchar_t* s; wchar_t* t; int nLen; int nLine = 0; int nInside = 0; TCHAR* nResourceType = 0; if (pszFilename == 0 || _tcslen(pszFilename) == 0) { return -1; } memset(&CurrentResource, 0, sizeof(LocaliseResourceInfo)); FILE* h = _tfopen(pszFilename, _T("rb")); if (h == NULL) { return 1; } { unsigned char szBOM[4] = { 0, }; fread(szBOM, 1, sizeof(szBOM), h); // See if it's a UTF-8 file if (szBOM[0] == 0xEF && szBOM[1] == 0xBB && szBOM[2] == 0xBF) { nFBACodepage = CP_UTF8; } #ifdef _UNICODE // See if it's a UTF-16 file if (szBOM[0] == 0xFF && szBOM[1] == 0xFE) { nFBACodepage = CP_WINUNICODE; fseek(h, 2, SEEK_SET); } #endif } if (nFBACodepage != CP_WINUNICODE) { fclose(h); h = _tfopen(pszFilename, _T("rt")); if (h == NULL) { return 1; } if (nFBACodepage == CP_UTF8) { fseek(h, 3, SEEK_SET); } } while (1) { char szTemp[1024]; #ifdef _UNICODE if (nFBACodepage != CP_WINUNICODE) { #endif if (fgets(szTemp, sizeof(szTemp), h) == NULL) { break; } MultiByteToWideChar(nFBACodepage, 0, szTemp, -1, szLine, sizeof(szLine) / sizeof(TCHAR)); #ifdef _UNICODE } else { if (_fgetts(szLine, sizeof(szLine), h) == NULL) { break; } } #endif nLine++; nLen = wcslen(szLine); // Get rid of the linefeed at the end while (szLine[nLen - 1] == 0x0A || szLine[nLen - 1] == 0x0D) { szLine[nLen - 1] = 0; nLen--; } s = szLine; // Start parsing WSKIP_WS(s); if (s[0] == _T('/') && s[1] == _T('/')) { // Comment continue; } if ((t = LabelCheckW(s, L"version")) != 0) { // Version s = t; WSKIP_WS(s); nTemplateVersion = wcstol(s, &t, 0); if (s != t) { if (nTemplateVersion != nBurnVer) { break; } } #ifdef PRINT_TRANSLATION_INFO dprintf(_T("version\n"), nTemplateVersion); #endif s = t; continue; } if ((t = LabelCheckW(s, L"codepage")) != 0) { // Set codepage s = t; WSKIP_WS(s); nFBACodepage = wcstol(s, &t, 0); #ifdef PRINT_TRANSLATION_INFO dprintf(_T("codepage\n"), nFBACodepage); #endif s = t; continue; } if ((t = LabelCheckW(s, L"menu")) != 0) { s = t; nResourceType = RT_MENU; WSKIP_WS(s); unsigned int nID = wcstol(s, &t, 0); #ifdef PRINT_TRANSLATION_INFO dprintf(_T("menu %i\n"), nID); #endif s = t; WSKIP_WS(s); if (nInside) { FBALocaliseError(pszFilename, nLine, _T("missing closing bracket"), NULL); break; } if (*s != _T('{')) { FBALocaliseError(pszFilename, nLine, _T("missing opening bracket"), NULL); break; } nInside = 1; CurrentResource.nID = nID; continue; } if ((t = LabelCheckW(s, L"dialog")) != 0) { // Add new resource s = t; nResourceType = RT_DIALOG; WSKIP_WS(s); unsigned int nID = wcstol(s, &t, 0); #ifdef PRINT_TRANSLATION_INFO dprintf(_T("dialog %i\n"), nID); #endif s = t; // Read dialog caption wchar_t* szQuote = NULL; wchar_t* szEnd = NULL; QuoteReadW(&szQuote, &szEnd, s); s = szEnd; WSKIP_WS(s); if (nInside) { FBALocaliseError(pszFilename, nLine, _T("missing closing bracket"), NULL); break; } if (*s != L'{') { FBALocaliseError(pszFilename, nLine, _T("missing opening bracket"), NULL); break; } nInside = 1; CurrentResource.nID = nID; if (wcslen(szQuote)) { memcpy(CurrentResource.szCaption, szQuote, QUOTE_MAX * sizeof(TCHAR)); } continue; } if ((t = LabelCheckW(s, L"string")) != 0) { s = t; if (nInside) { FBALocaliseError(pszFilename, nLine, _T("missing closing bracket"), NULL); break; } WSKIP_WS(s); unsigned int nID = wcstol(s, &t, 0); s = t; // Read dialog caption WFIND_QT(s); s++; wchar_t* szQuote = s; WFIND_QT(s); wchar_t* szEnd = s; if (nID < nMaxResources) { #ifdef PRINT_TRANSLATION_INFO { TCHAR szFormat[256]; _stprintf(szFormat, _T("string %%5i \"%%.%ils\"\n"), szEnd - szQuote); dprintf(szFormat, nID, szQuote); } #endif if (szEnd - szQuote > 0) { UnEscapeString(wszBuffer, szQuote, szEnd - szQuote); FBAResourceInfo[nID].nResourceFlags = RES_DEALLOCATE; #ifdef _UNICODE FBAResourceInfo[nID].pResourceTranslation = malloc((wcslen(wszBuffer) + 1) * sizeof(wchar_t)); wcscpy((wchar_t*)FBAResourceInfo[nID].pResourceTranslation, wszBuffer); #else { char szStringBuffer[5120]; memset(szStringBuffer, 0, sizeof(szStringBuffer)); WideCharToMultiByte(CP_ACP, 0, wszBuffer, -1, szStringBuffer, 5120, NULL, NULL); FBAResourceInfo[nID].pResourceTranslation = malloc((strlen(szStringBuffer) + 1)); strcpy((char*)FBAResourceInfo[nID].pResourceTranslation, szStringBuffer); } #endif } } } int n = wcstol(s, &t, 0); bool bPopup = false; if (t == s) { t = LabelCheckW(s, L"popup"); bPopup = true; } if (t && t != s) { // New control if (nInside == 0) { FBALocaliseError(pszFilename, nLine, _T("rogue control statement"), szLine); break; } s = t; n = wcstol(s, &t, 0); // Link a new control info structure if (n < 256) { s = t; // Read option name wchar_t* szQuote = NULL; wchar_t* szEnd = NULL; if (QuoteReadW(&szQuote, &szEnd, s)) { FBALocaliseError(pszFilename, nLine, _T("control name omitted"), szLine); break; } s = szEnd; if (bPopup) { WSKIP_WS(s); if (*s != L'{') { FBALocaliseError(pszFilename, nLine, _T("missing opening bracket"), NULL); break; } nInside++; } if (wcslen(szQuote)) { if (CurrentResource.pControlInfo[n] == NULL) { CurrentResource.pControlInfo[n] = (LocaliseControlInfo*)malloc(sizeof(LocaliseControlInfo)); } memset(CurrentResource.pControlInfo[n], 0, sizeof(LocaliseControlInfo)); memcpy(CurrentResource.pControlInfo[n]->szCaption, szQuote, QUOTE_MAX * sizeof(TCHAR)); } // dprintf(_T(" - %ls\n"), pCurrentResource->pControlInfo[n]->szCaption); } continue; } WSKIP_WS(s); if (*s == L'}') { if (nInside == 0) { FBALocaliseError(pszFilename, nLine, _T("rogue closing bracket"), NULL); break; } nInside--; if (nInside == 0) { if (CurrentResource.nID < nMaxResources) { if (nResourceType == RT_MENU) { MENUTEMPLATE* pTemplate; pTemplate = (MENUTEMPLATE*)LoadResource(hAppInst, FindResource(hAppInst, MAKEINTRESOURCE(CurrentResource.nID), RT_MENU)); if (LockResource((HGLOBAL)pTemplate)) { if (((MENUITEMTEMPLATEHEADER*)pTemplate)->versionNumber == 0) { // Translate the structure FBAResourceInfo[CurrentResource.nID].pResourceTranslation = TranslateMenuTemplate((MENUTEMPLATE*)pTemplate, &CurrentResource); FBAResourceInfo[CurrentResource.nID].nResourceFlags = RES_DEALLOCATE; } } } if (nResourceType == RT_DIALOG) { LPCDLGTEMPLATE pTemplate; pTemplate = (LPCDLGTEMPLATE)LoadResource(hAppInst, FindResource(hAppInst, MAKEINTRESOURCE(CurrentResource.nID), RT_DIALOG)); if (LockResource((HGLOBAL)pTemplate)) { if (((DLGTEMPLATEEX*)pTemplate)->signature == 0xFFFF && ((DLGTEMPLATEEX*)pTemplate)->dlgVer == 1) { // Translate the structure FBAResourceInfo[CurrentResource.nID].pResourceTranslation = TranslateDlgTemplateEx((DLGTEMPLATEEX*)pTemplate, &CurrentResource); FBAResourceInfo[CurrentResource.nID].nResourceFlags = RES_DEALLOCATE; } } } } for (int i = 0; i < 1024; i++) { free(CurrentResource.pControlInfo[i]); } memset(&CurrentResource, 0, sizeof(LocaliseResourceInfo)); } } // Line isn't (part of) a valid cheat #if 0 if (*s) { FBALocaliseError(pszFilename, nLine, _T("rogue line"), szLine); break; } #endif } for (int i = 0; i < 1024; i++) { free(CurrentResource.pControlInfo[i]); } if (h) { fclose(h); } if (nTemplateVersion != nBurnVer) { if (nTemplateVersion == 0) { return -1; } return -2; } return 0; }
bool DoPrepared(HDBC lpDbc, TCHAR* szInput) { int arrIdx = 0; RETCODE RetCode; SQLSMALLINT sNumResults; HSTMT lpStmt = NULL; TCHAR* szIter = szInput; int cnt = 0; TRYODBCP(lpDbc, SQL_HANDLE_DBC, SQLAllocHandle(SQL_HANDLE_STMT, lpDbc, &lpStmt)); RetCode = SQLPrepare(lpStmt, (SQLCHAR*) szInput, SQL_NTS); while (NULL != (szIter = strstr(szIter, "?"))) { ++cnt; ++szIter; } TCHAR szParams[MAX_PARAMS][SQL_QUERY_SIZE]; SQLLEN lenParams[MAX_PARAMS]; for (int sqlIdx = 1; sqlIdx <= cnt; ++sqlIdx) { arrIdx = sqlIdx - 1; _fgetts(szParams[arrIdx], SQL_QUERY_SIZE - 1, stdin); lenParams[arrIdx] = strlen(szParams[arrIdx]); szParams[arrIdx][lenParams[arrIdx]] = '\0'; lenParams[arrIdx] -= 1; TRYODBCP(lpStmt, SQL_HANDLE_STMT, SQLBindParameter(lpStmt, sqlIdx, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 255, 0, szParams[arrIdx], SQL_QUERY_SIZE, &lenParams[arrIdx])); } RetCode = SQLExecute(lpStmt); switch (RetCode) { case SQL_SUCCESS_WITH_INFO: { HandleError(lpStmt, SQL_HANDLE_STMT, RetCode); // fall through } case SQL_SUCCESS: { // If this is a row-returning query, display // results TRYODBCP(lpStmt, SQL_HANDLE_STMT, SQLNumResultCols(lpStmt, &sNumResults)); if (sNumResults > 0) { DisplayResults(lpStmt, sNumResults); } else { SQLLEN siRowCount; TRYODBCP(lpStmt, SQL_HANDLE_STMT, SQLRowCount(lpStmt, &siRowCount)); if (siRowCount >= 0) { _tprintf(TEXT("%ld %s affected\n"), static_cast<long>(siRowCount), siRowCount == 1 ? TEXT("row") : TEXT("rows")); } } break; } case SQL_ERROR: { HandleError(lpStmt, SQL_HANDLE_STMT, RetCode); break; } default: fprintf(stderr, "Unexpected return code %d!\n", RetCode); } SQLFreeStmt(lpStmt, SQL_DROP); return true; ExitP: return false; }
//---------------------------------------------------------------------- // // WMain // // Engine. Just get command line switches and fire off a format. This // could also be done in a GUI like Explorer does when you select a // drive and run a check on it. // // We do this in UNICODE because the chkdsk command expects PWCHAR // arguments. // //---------------------------------------------------------------------- int _tmain(int argc, TCHAR *argv[]) { int badArg; DWORD media = FMIFS_HARDDISK; DWORD driveType; TCHAR fileSystem[1024]; TCHAR volumeName[1024]; TCHAR input[1024]; DWORD serialNumber; DWORD flags, maxComponent; ULARGE_INTEGER freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes; #ifndef UNICODE WCHAR RootDirectoryW[MAX_PATH], FormatW[MAX_PATH], LabelW[MAX_PATH]; #endif TCHAR szMsg[RC_STRING_MAX_SIZE]; // // Get function pointers // if( !LoadFMIFSEntryPoints()) { LoadStringAndOem( GetModuleHandle(NULL), STRING_FMIFS_FAIL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf("%s", szMsg); return -1; } // // Parse command line // if( (badArg = ParseCommandLine( argc, argv ))) { LoadStringAndOem( GetModuleHandle(NULL), STRING_UNKNOW_ARG, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, argv[badArg] ); Usage(argv[0]); return -1; } // // Get the drive's format // if( !Drive ) { LoadStringAndOem( GetModuleHandle(NULL), STRING_DRIVE_PARM, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg); Usage( argv[0] ); return -1; } else { _tcscpy( RootDirectory, Drive ); } RootDirectory[2] = _T('\\'); RootDirectory[3] = _T('\0'); // // See if the drive is removable or not // driveType = GetDriveType( RootDirectory ); if( driveType == 0 ) { LoadStringAndOem( GetModuleHandle(NULL), STRING_ERROR_DRIVE_TYPE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error( szMsg, GetLastError()); return -1; } else if ( driveType == 1 ) { LoadString( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error( szMsg, GetLastError()); return -1; } if( driveType != DRIVE_FIXED ) { LoadStringAndOem( GetModuleHandle(NULL), STRING_INSERT_DISK, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, RootDirectory[0] ); _fgetts( input, sizeof(input)/2, stdin ); media = FMIFS_FLOPPY; } // // Determine the drive's file system format // if( !GetVolumeInformation( RootDirectory, volumeName, sizeof(volumeName)/2, &serialNumber, &maxComponent, &flags, fileSystem, sizeof(fileSystem)/2)) { LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error( szMsg, GetLastError()); return -1; } if( !GetDiskFreeSpaceEx( RootDirectory, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes )) { LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME_SIZE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error( szMsg, GetLastError()); return -1; } LoadStringAndOem( GetModuleHandle(NULL), STRING_FILESYSTEM, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, fileSystem ); // // Make sure they want to do this // if( driveType == DRIVE_FIXED ) { if( volumeName[0] ) { while(1 ) { LoadStringAndOem( GetModuleHandle(NULL), STRING_LABEL_NAME_EDIT, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, RootDirectory[0] ); _fgetts( input, sizeof(input)/2, stdin ); input[ _tcslen( input ) - 1] = 0; if( !_tcsicmp( input, volumeName )) { break; } LoadStringAndOem( GetModuleHandle(NULL), STRING_ERROR_LABEL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf("%s", szMsg); } } LoadStringAndOem( GetModuleHandle(NULL), STRING_YN_FORMAT, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, RootDirectory[0] ); LoadStringAndOem( GetModuleHandle(NULL), STRING_YES_NO_FAQ, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); while( 1 ) { _fgetts( input, sizeof(input)/2, stdin ); if(_strnicmp(&input[0],&szMsg[0],1) == 0) break; if(_strnicmp(&input[0],&szMsg[1],1) == 0) { _tprintf(_T("\n")); return 0; } } media = FMIFS_HARDDISK; } // // Tell the user we're doing a long format if appropriate // if( !QuickFormat ) { LoadString( GetModuleHandle(NULL), STRING_VERIFYING, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); if( totalNumberOfBytes.QuadPart > 1024*1024*10 ) { _tprintf(_T("%s %luM\n"),szMsg, (DWORD) (totalNumberOfBytes.QuadPart/(1024*1024))); } else { _tprintf(_T("%s %.1fM\n"),szMsg, ((float)(LONGLONG)totalNumberOfBytes.QuadPart)/(float)(1024.0*1024.0)); } } else { LoadStringAndOem( GetModuleHandle(NULL), STRING_FAST_FMT, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); if( totalNumberOfBytes.QuadPart > 1024*1024*10 ) { _tprintf(_T("%s %luM\n"),szMsg, (DWORD) (totalNumberOfBytes.QuadPart/(1024*1024))); } else { _tprintf(_T("%s %.2fM\n"),szMsg, ((float)(LONGLONG)totalNumberOfBytes.QuadPart)/(float)(1024.0*1024.0)); } LoadStringAndOem( GetModuleHandle(NULL), STRING_CREATE_FSYS, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf("%s", szMsg); } // // Format away! // #ifndef UNICODE MultiByteToWideChar(CP_ACP, 0, RootDirectory, -1, RootDirectoryW, MAX_PATH); MultiByteToWideChar(CP_ACP, 0, Format, -1, FormatW, MAX_PATH); MultiByteToWideChar(CP_ACP, 0, Label, -1, LabelW, MAX_PATH); FormatEx( RootDirectoryW, media, FormatW, LabelW, QuickFormat, ClusterSize, FormatExCallback ); #else FormatEx( RootDirectory, media, Format, Label, QuickFormat, ClusterSize, FormatExCallback ); #endif if( Error ) return -1; LoadStringAndOem( GetModuleHandle(NULL), STRING_FMT_COMPLETE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf("%s", szMsg); // // Enable compression if desired // if( CompressDrive ) { #ifndef UNICODE MultiByteToWideChar(CP_ACP, 0, RootDirectory, -1, RootDirectoryW, MAX_PATH); if( !EnableVolumeCompression( RootDirectoryW, TRUE )) { #else if( !EnableVolumeCompression( RootDirectory, TRUE )) { #endif LoadStringAndOem( GetModuleHandle(NULL), STRING_VOL_COMPRESS, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf("%s", szMsg); } } // // Get the label if we don't have it // if( !GotALabel ) { LoadString( GetModuleHandle(NULL), STRING_ENTER_LABEL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf("%s", szMsg); _fgetts( input, sizeof(LabelString)/2, stdin ); input[ _tcslen(input)-1] = 0; if( !SetVolumeLabel( RootDirectory, input )) { LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_LABEL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error(szMsg, GetLastError()); return -1; } } if( !GetVolumeInformation( RootDirectory, volumeName, sizeof(volumeName)/2, &serialNumber, &maxComponent, &flags, fileSystem, sizeof(fileSystem)/2)) { LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error( szMsg, GetLastError()); return -1; } // // Print out some stuff including the formatted size // if( !GetDiskFreeSpaceEx( RootDirectory, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes )) { LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME_SIZE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error(szMsg, GetLastError()); return -1; } LoadStringAndOem( GetModuleHandle(NULL), STRING_FREE_SPACE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, totalNumberOfBytes.QuadPart, totalNumberOfFreeBytes.QuadPart ); // // Get the drive's serial number // if( !GetVolumeInformation( RootDirectory, volumeName, sizeof(volumeName)/2, &serialNumber, &maxComponent, &flags, fileSystem, sizeof(fileSystem)/2)) { LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); PrintWin32Error( szMsg, GetLastError()); return -1; } LoadStringAndOem( GetModuleHandle(NULL), STRING_SERIAL_NUMBER, (LPTSTR) szMsg,RC_STRING_MAX_SIZE); _tprintf(szMsg, (unsigned int)(serialNumber >> 16), (unsigned int)(serialNumber & 0xFFFF) ); return 0; }
int _tmain(int argc, LPTSTR argv[]) { HANDLE hIn, hOut; DWORD nIn, nOut, n; BOOL finish = FALSE; TCHAR input[L]; TCHAR cmd; LARGE_INTEGER offset; Student s; /* Check number of arguments */ if(argc != 2) { _ftprintf(stderr, _T("Wrong number of arguments. Usage: %s fileIn\n"), argv[0]); return -1; } while (!finish) { _ftprintf(stdout, _T("Enter a command:\n")); _fgetts(input, L, stdin); cmd = input[0]; /* Case E */ if (cmd == 'E') { finish = TRUE; } /* Case R */ if (cmd == 'R') { _stscanf(input, _T("%*c %i"), &n); hIn = CreateFile(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hIn == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Error opening the file for reading: %i\n"), GetLastError()); return -2; } if (n > 1) { offset.QuadPart = (n - 1) * sizeof(Student); if (!SetFilePointerEx(hIn, offset, NULL, FILE_BEGIN)) { _ftprintf(stderr, _T("Error setting the pointer: %i\n"), GetLastError()); return -3; } } if (ReadFile(hIn, &s, sizeof(Student), &nIn, NULL) && (nIn > 0)) { _ftprintf(stdout, _T("%i %i %s %s %i\n"), s.id, s.number, s.name, s.surname, s.mark); } else { _ftprintf(stderr, _T("Error reading the file: %i\n"), GetLastError()); return -4; } CloseHandle(hIn); } /* Case W */ if (cmd == 'W') { _stscanf(input, _T("%*c %i"), &n); hOut = CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hOut == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Error opening the file for writing: %i\n"), GetLastError()); return -5; } _ftprintf(stdout, _T("Enter a new record:\n")); _ftscanf(stdin, _T("%i %i %s %s %i"), &s.id, &s.number, s.name, s.surname, &s.mark); if (n > 1) { offset.QuadPart = (n - 1) * sizeof(Student); if (!SetFilePointerEx(hOut, offset, NULL, FILE_BEGIN)) { _ftprintf(stderr, _T("Error setting the pointer: %i\n"), GetLastError()); return -6; } } if (!WriteFile(hOut, &s, sizeof(Student), &nOut, NULL) || (nOut != sizeof(Student))) { _ftprintf(stderr, _T("Error writing the file: %i\n"), GetLastError()); return -7; } CloseHandle(hOut); } } return 0; }
static int isowavParseCueFile() { TCHAR szLine[1024]; TCHAR szFile[1024]; TCHAR* s; TCHAR* t; FILE* h; int track = 0; int length; isowavTOC->FirstTrack = 1; isowavTOC->LastTrack = 1; isowavTOC->TrackData[0].Address[1] = 0; isowavTOC->TrackData[0].Address[2] = 2; isowavTOC->TrackData[0].Address[3] = 0; h = _tfopen(CDEmuImage, _T("rt")); if (h == NULL) { return 1; } while (1) { if (_fgetts(szLine, sizeof(szLine), h) == NULL) { break; } length = _tcslen(szLine); // get rid of the linefeed at the end while (length && (szLine[length - 1] == _T('\r') || szLine[length - 1] == _T('\n'))) { szLine[length - 1] = 0; length--; } s = szLine; // file info if ((t = LabelCheck(s, _T("FILE"))) != 0) { s = t; TCHAR* szQuote; // read filename QuoteRead(&szQuote, NULL, s); _sntprintf(szFile, ExtractFilename(CDEmuImage) - CDEmuImage, _T("%s"), CDEmuImage); _sntprintf(szFile + (ExtractFilename(CDEmuImage) - CDEmuImage), 1024 - (ExtractFilename(CDEmuImage) - CDEmuImage), _T("/%s"), szQuote); continue; } // track info if ((t = LabelCheck(s, _T("TRACK"))) != 0) { s = t; // track number track = _tcstol(s, &t, 10); if (track < 1 || track > MAXIMUM_NUMBER_TRACKS) { fclose(h); return 1; } if (track < isowavTOC->FirstTrack) { isowavTOC->FirstTrack = track; } if (track > isowavTOC->LastTrack) { isowavTOC->LastTrack = track; } isowavTOC->TrackData[track - 1].TrackNumber = track; isowavTOC->TrackData[track - 1].Filename = (TCHAR*)malloc((_tcslen(szFile) + 1) * sizeof(TCHAR)); if (isowavTOC->TrackData[track - 1].Filename == NULL) { fclose(h); return 1; } _tcscpy(isowavTOC->TrackData[track - 1].Filename, szFile); s = t; // type of track if ((t = LabelCheck(s, _T("MODE1/2048"))) != 0) { isowavTOC->TrackData[track - 1].Control = 4; continue; } if ((t = LabelCheck(s, _T("AUDIO"))) != 0) { isowavTOC->TrackData[track - 1].Control = 0; continue; } fclose(h); return 1; } // pregap if ((t = LabelCheck(s, _T("PREGAP"))) != 0) { s = t; int M, S, F; // pregap M M = _tcstol(s, &t, 10); s = t + 1; // pregap S S = _tcstol(s, &t, 10); s = t + 1; // pregap F F = _tcstol(s, &t, 10); if (M < 0 || M > 100 || S < 0 || S > 59 || F < 0 || F > 74) { fclose(h); return 1; } isowavTOC->TrackData[track - 1].Address[1] = M; isowavTOC->TrackData[track - 1].Address[2] = S; isowavTOC->TrackData[track - 1].Address[3] = F; continue; } } fclose(h); return isowavGetTrackSizes(); }
/** * \brief */ bool Settings::Load() { SetDefaults(); CPath cfgFile; INpp::Get().GetPluginsConfDir(cfgFile); cfgFile += cPluginCfgFileName; if (!cfgFile.FileExists()) return false; FILE* fp; _tfopen_s(&fp, cfgFile.C_str(), _T("rt")); if (fp == NULL) return false; bool success = true; TCHAR line[8192]; while (_fgetts(line, _countof(line), fp)) { // Comment or empty line if (line[0] == _T('#') || line[0] == _T('\n')) continue; // Strip newline from the end of the line line[_tcslen(line) - 1] = 0; if (!_tcsncmp(line, cUseDefDbKey, _countof(cUseDefDbKey) - 1)) { const unsigned pos = _countof(cUseDefDbKey) - 1; if (!_tcsncmp(&line[pos], _T("yes"), _countof(_T("yes")) - 1)) _useDefDb = true; else _useDefDb = false; } else if (!_tcsncmp(line, cDefDbPathKey, _countof(cDefDbPathKey) - 1)) { const unsigned pos = _countof(cDefDbPathKey) - 1; _defDbPath = &line[pos]; _defDbPath.AsFolder(); if (!_defDbPath.Exists()) _defDbPath.Clear(); } else if (!_tcsncmp(line, cREOptionKey, _countof(cREOptionKey) - 1)) { const unsigned pos = _countof(cREOptionKey) - 1; if (!_tcsncmp(&line[pos], _T("yes"), _countof(_T("yes")) - 1)) _re = true; else _re = false; } else if (!_tcsncmp(line, cICOptionKey, _countof(cICOptionKey) - 1)) { const unsigned pos = _countof(cICOptionKey) - 1; if (!_tcsncmp(&line[pos], _T("yes"), _countof(_T("yes")) - 1)) _ic = true; else _ic = false; } else if (!_genericDbCfg.ReadOption(line)) { success = false; SetDefaults(); break; } } fclose(fp); return success; }