static int nextspecs (char ***field) { static char **fld = NULL; static FILE *fp = NULL; static int eof = 0; static int fld_size = 0; static int line_number = 0; int nfield = 0; /* all done if end of file found on prior call */ if (eof) { fclose (fp); free (fld); return (0); } /* initialize on the first call */ if (fp == NULL) { fopen_s(&fp, "output.opt", "r"); if (fp == NULL) error_stop ("cannot open file", "output.opt"); fld_size = 100; fld = (char **) malloc ((unsigned) fld_size * sizeof (char *)); if (fld == NULL) error_stop ("cannot allocate vector fld", "for output.opt specs"); } /* get specs from the next non-blank line */ while (1) { char buf[200]; char cur_line[50]; char *line; int cur_fld_len; int line_continued; int eol_found = 0; /* read the next line */ line = fgets (buf, 200, fp); ++line_number; sprintf_s (cur_line, sizeof(cur_line), "line %d of file output.opt", line_number); if (line == NULL) { eof = 1; break; } /* find the fields on the line */ cur_fld_len = 0; line_continued = 0; while (*line) { if (*line == '"') { if (cur_fld_len > 0) error_stop ("embedded quote on", cur_line); while (++line) { if (*line == '\0' || *line == '\n') error_stop ("missing quote on", cur_line); if (*line == '"') { *line = ' '; break; } ++cur_fld_len; } } if ((*line == '/' && *(line + 1) == '/') || *line == '\n') eol_found = 1; if (*line == '+' && *(line + 1) == '+') { eol_found = 1; line_continued = 1; { char *p = line + 2; while (*p && *p != '\n') { if (*p == '/' && *(p + 1) == '/') break; if (*p != ' ' && *p != '\t') error_stop ("characters after ++ on", cur_line); ++p; } } } if (*line == ' ' || *line == '\t' || eol_found) { if (cur_fld_len > 0) { if (nfield == fld_size) { fld_size += 100; fld = (char **) realloc (fld, (unsigned) fld_size * sizeof (char *)); if (fld == NULL) error_stop ("cannot reallocate vector fld on", cur_line); } fld[nfield] = (char *) malloc ((unsigned) cur_fld_len + 1); if (fld[nfield] == NULL) error_stop ("cannot allocate space for option spec on", cur_line); *line = '\0'; strcpy_s(fld[nfield++], cur_fld_len + 1, line - cur_fld_len); cur_fld_len = 0; } } else ++cur_fld_len; if (eol_found) break; ++line; } if (! eol_found) error_stop ("line is too long -", cur_line); /* stop reading if field(s) found and line not continued */ if (nfield > 0 && ! line_continued) break; } /* set output arguments and return */ *field = fld; return (nfield); }
bool TerrainClass::LoadColorMap(char* filename) { int error, imageSize, i, j, k, index, colorMapWidth, colorMapHeight; FILE* filePtr; unsigned int count; BITMAPFILEHEADER bitmapFileHeader; BITMAPINFOHEADER bitmapInfoHeader; unsigned char* bitmapImage; // Open the color map file in binary. error = fopen_s(&filePtr, filename, "rb"); if(error != 0) { return false; } // Read in the file header. count = fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr); if(count != 1) { return false; } // Read in the bitmap info header. count = fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr); if(count != 1) { return false; } // Make sure the color map dimensions are the same as the terrain dimensions for easy 1 to 1 mapping. colorMapWidth = bitmapInfoHeader.biWidth; colorMapHeight = bitmapInfoHeader.biHeight; if((colorMapWidth != m_terrainWidth) || (colorMapHeight != m_terrainHeight)) { return false; } // Calculate the size of the bitmap image data. imageSize = colorMapWidth * colorMapHeight * 3; // Allocate memory for the bitmap image data. bitmapImage = new unsigned char[imageSize]; if(!bitmapImage) { return false; } // Move to the beginning of the bitmap data. fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET); // Read in the bitmap image data. count = fread(bitmapImage, 1, imageSize, filePtr); if(count != imageSize) { return false; } // Close the file. error = fclose(filePtr); if(error != 0) { return false; } // Initialize the position in the image data buffer. k=0; // Read the image data into the color map portion of the height map structure. for(j=0; j<colorMapHeight; j++) { for(i=0; i<colorMapWidth; i++) { index = (colorMapHeight * j) + i; m_heightMap[index].b = (float)bitmapImage[k] / 255.0f; m_heightMap[index].g = (float)bitmapImage[k+1] / 255.0f; m_heightMap[index].r = (float)bitmapImage[k+2] / 255.0f; k+=3; } } // Release the bitmap image data. delete [] bitmapImage; bitmapImage = 0; return true; }
BOOL CItemSystemFor380::Load380ItemOptionInfo(LPSTR filename) { enum SMDToken Token; if (fopen_s(&SMDFile,filename, "r") != 0 ) { return FALSE; } this->_InitOption(); while ( true ) { Token = (SMDToken)GetToken(); if ( Token == END ) break; if ( Token == NUMBER ) { int Index = (int)TokenNumber; while ( true ) { Token = (SMDToken)GetToken(); int _type = (int)TokenNumber; if ( Token == NAME ) { if ( !strcmp("end", TokenString)) { break; } } Token = (SMDToken)GetToken(); int _index = (int)TokenNumber; ITEMOPTION_FOR380ITEM * p = &this->m_itemOption[ITEMGET(_type, _index)]; p->IsLoad = TRUE; p->m_Type = _type; p->m_Index = _index; Token = (SMDToken)GetToken(); p->m_Option1 = (BYTE)TokenNumber; Token = (SMDToken)GetToken(); p->m_Value1 = (WORD)TokenNumber; Token = (SMDToken)GetToken(); p->m_Option2 = (BYTE)TokenNumber; Token = (SMDToken)GetToken(); p->m_Value2 = (WORD)TokenNumber; Token = (SMDToken)GetToken(); int iTime = (int)TokenNumber; } } } fclose(SMDFile); return TRUE; }
void MeshFileData::Create(const char* filename){ this->~MeshFileData(); FILE *hFP; fopen_s(&hFP, filename, "rb"); if (hFP == 0)return; std::string str = filename; auto type = behind_than_find_last_of(str, "."); IPolygonsData* _data = NULL; if (type == "tesmesh"){ auto buf = new PolygonsData<SimpleVertex, unsigned short, int>(); fstd::r_vector(buf->Vertexs, hFP); fstd::r_vector(buf->Indices, hFP); fstd::r_vector(buf->Meshs, hFP); auto data = new PolygonsData<SimpleVertexNormal, unsigned short, int>(); data->Indices = std::move(buf->Indices); data->Meshs = std::move(buf->Meshs); auto vnum = buf->Vertexs.size(); //data->Vertexs.resize(vnum); auto num = data->Indices.size(); data->Vertexs.resize(num); for (int i = 0; i < num; i+=3){ int i0 = data->Indices[i + 0]; int i1 = data->Indices[i + 1]; int i2 = data->Indices[i + 2]; int o0 = data->Indices[i + 0] = i + 0; int o1 = data->Indices[i + 1] = i + 1; int o2 = data->Indices[i + 2] = i + 2; data->Vertexs[o0].Pos = buf->Vertexs[i0].Pos; data->Vertexs[o1].Pos = buf->Vertexs[i1].Pos; data->Vertexs[o2].Pos = buf->Vertexs[i2].Pos; data->Vertexs[o0].Normal = buf->Vertexs[i0].Normal; data->Vertexs[o1].Normal = buf->Vertexs[i1].Normal; data->Vertexs[o2].Normal = buf->Vertexs[i2].Normal; data->Vertexs[o0].Tex = buf->Vertexs[i0].Tex; data->Vertexs[o1].Tex = buf->Vertexs[i1].Tex; data->Vertexs[o2].Tex = buf->Vertexs[i2].Tex; auto& p0 = data->Vertexs[o0]; auto& p1 = data->Vertexs[o1]; auto& p2 = data->Vertexs[o2]; CalcTangentAndBinormal(p0, p1, p2); //SimpleVertexNormal center; //SimpleVertexNormal x; //SimpleVertexNormal y; // //if (p0.Tex.y == p1.Tex.y && p0.Tex.x == p2.Tex.x){ // center = p0; // x = p1; // y = p2; //} //else if (p0.Tex.x == p1.Tex.x && p0.Tex.y == p2.Tex.y){ // center = p0; // x = p2; // y = p1; //} // //else if (p1.Tex.y == p0.Tex.y && p1.Tex.x == p2.Tex.x){ // center = p1; // x = p0; // y = p2; //} //else if (p1.Tex.x == p0.Tex.x && p1.Tex.y == p2.Tex.y){ // center = p1; // x = p2; // y = p0; //} // //else if (p2.Tex.y == p1.Tex.y && p0.Tex.x == p2.Tex.x){ // center = p2; // x = p1; // y = p0; //} //else{//if (p2.Tex.x == p1.Tex.x && p0.Tex.y == p2.Tex.y){ // center = p2; // x = p0; // y = p1; //} // //XMVECTOR bin; //XMVECTOR tan; //if (center.Tex.x < x.Tex.x){ // bin = XMVectorSet(x.Pos.x, x.Pos.y, x.Pos.z, 1) - XMVectorSet(center.Pos.x, center.Pos.y, center.Pos.z, 0); //} //else{ // bin = XMVectorSet(center.Pos.x, center.Pos.y, center.Pos.z, 1) - XMVectorSet(x.Pos.x, x.Pos.y, x.Pos.z, 0); //} //if (center.Tex.y < y.Tex.y){ // tan = XMVectorSet(y.Pos.x, y.Pos.y, y.Pos.z, 1) - XMVectorSet(center.Pos.x, center.Pos.y, center.Pos.z, 0); //} //else{ // tan = XMVectorSet(center.Pos.x, center.Pos.y, center.Pos.z, 1) - XMVectorSet(y.Pos.x, y.Pos.y, y.Pos.z, 0); //} // // ////auto bin = XMVectorSet(p1.Pos.x, p1.Pos.y, p1.Pos.z, 1) - XMVectorSet(p0.Pos.x, p0.Pos.y, p0.Pos.z, 0); ////bin = XMVector3Normalize(bin); ////auto n = XMVectorSet(p0.Normal.x, p0.Normal.y, p0.Normal.z, 0); ////auto tan = XMVector3Cross(n, bin); // ////BinormalとTangent計算 //data->Vertexs[o0].Binormal = XMFLOAT3(bin.x, bin.y, bin.z); //data->Vertexs[o1].Binormal = XMFLOAT3(bin.x, bin.y, bin.z); //data->Vertexs[o2].Binormal = XMFLOAT3(bin.x, bin.y, bin.z); //data->Vertexs[o0].Tangent = XMFLOAT3(tan.x, tan.y, tan.z); //data->Vertexs[o1].Tangent = XMFLOAT3(tan.x, tan.y, tan.z); //data->Vertexs[o2].Tangent = XMFLOAT3(tan.x, tan.y, tan.z); } delete buf; _data = data; }else if (type == "tedmesh"){ auto data = new PolygonsData<SimpleBoneVertex, unsigned short, int>(); fstd::r_vector(data->Vertexs, hFP); fstd::r_vector(data->Indices, hFP); fstd::r_vector(data->Meshs, hFP); _data = data; } m_Polygons = _data; fclose(hFP); }
int readDWI(std::vector<struct ARROW> *chart, std::vector<struct FREEZE> *holds, int songID, int chartType) { char filename[] = "DATA/dwis/101.dwi"; FILE* fp = NULL; std::vector<struct BEAT_NOTE> beats; // hopefully open the target DWI file filename[10] = (songID/100 % 10) + '0'; filename[11] = (songID/10 % 10) + '0'; filename[12] = (songID % 10) + '0'; if ( fopen_s(&fp, filename, "rt") != 0 ) { // as a fall back, open a memory dump of a chart (legacy chart data) return readDMXSQ(chart, holds, songID, chartType); } // fix any potential bugs regarding data from one chart accidentally merging into the next chart chart->clear(); holds->clear(); int gap = 0; float timePerBeat = 400.0; // 150 BPM // start reading tags readNextTag(fp); while ( tagName[0] != 0 ) { if ( _strcmpi("SINGLE", tagName) == 0 ) { if ( _strcmpi("BASIC", tagValue) == 0 && chartType == SINGLE_MILD ) { processChartString(&beats, tagLeftSide, 0); } else if ( _strcmpi("ANOTHER", tagValue) == 0 && chartType == SINGLE_WILD ) { processChartString(&beats, tagLeftSide, 0); } else if ( _strcmpi("MANIAC", tagValue) == 0 && chartType == SINGLE_ANOTHER ) { processChartString(&beats, tagLeftSide, 0); } } if ( _strcmpi("DOUBLE", tagName) == 0 ) { if ( _strcmpi("BASIC", tagValue) == 0 && chartType == DOUBLE_MILD ) { processChartString(&beats, tagLeftSide, 0); processChartString(&beats, tagRightSide, 1); } else if ( _strcmpi("ANOTHER", tagValue) == 0 && chartType == DOUBLE_WILD ) { processChartString(&beats, tagLeftSide, 0); processChartString(&beats, tagRightSide, 1); } else if ( _strcmpi("MANIAC", tagValue) == 0 && chartType == DOUBLE_ANOTHER ) { processChartString(&beats, tagLeftSide, 0); processChartString(&beats, tagRightSide, 1); } } if ( _strcmpi("BPM", tagName) == 0 ) { float bpm = atof(tagValue); timePerBeat = BPM_TO_MSEC(bpm); // set the initial scroll rate // WHY DOES THIS MAKE SONG NOT END? affects end of song marker somehow? struct ARROW a; a.timing = 0; a.color = bpm; a.type = BPM_CHANGE; a.judgement = UNSET; chart->push_back(a); } if ( _strcmpi("GAP", tagName) == 0 ) { gap = atoi(tagValue); al_trace("gap = %d\r\n", gap); } if ( _strcmpi("CHANGEBPM", tagName) == 0 ) // #CHANGEBPM:992.000=95.000,1016.000=190.000; { char* token, *next; token = strtok_s(tagValue, ",;", &next); while ( token != NULL ) { char leftSide[32], rightSide[32]; char* equalsPos = strchr(token, '='); if ( equalsPos == NULL ) { continue; } strncpy_s(leftSide, token, equalsPos - token); strcpy_s(rightSide, equalsPos+1); struct BEAT_NOTE b; b.beat = atof(leftSide)/4.0; b.param = atof(rightSide); b.type = BPM_CHANGE; beats.push_back(b); token = strtok_s(NULL, ",;", &next); } } if ( _strcmpi("FREEZE", tagName) == 0 ) // #FREEZE:668.000=327.000,1292.000=967.000; { char* token, *next; token = strtok_s(tagValue, ",;", &next); while ( token != NULL ) { char leftSide[32], rightSide[32]; char* equalsPos = strchr(token, '='); if ( equalsPos == NULL ) { continue; } strncpy_s(leftSide, token, equalsPos - token); strcpy_s(rightSide, equalsPos+1); struct BEAT_NOTE b; b.beat = atof(leftSide)/4.0; b.param = atof(rightSide); b.type = SCROLL_STOP; beats.push_back(b); token = strtok_s(NULL, ",;", &next); } } // next loop readNextTag(fp); } sort(beats.begin(), beats.end(), sortNoteFunction); // for each item in the beats vector, create a struct ARROW (real chart object) and translate 'DWI beats' to milliseconds int numNotes = beats.size(); float currentTime = gap; float lastBeatProcessed = 0.0; for ( int i = 0; i < numNotes; i++ ) { struct ARROW a; struct FREEZE f; float beatsDifference = beats[i].beat - lastBeatProcessed; lastBeatProcessed = beats[i].beat; currentTime += timePerBeat*beatsDifference; if (currentTime < 0) { continue; // uh-oh; } al_trace("%f\r\n", currentTime); switch ( beats[i].type ) { case TAP: a.timing = currentTime; a.color = calculateArrowColor(a.timing, timePerBeat); a.type = TAP; a.columns[0] = beats[i].column; a.judgement = UNSET; chart->push_back(a); break; case HOLD_START: f.startTime = currentTime; f.columns[0] = beats[i].column; f.endTime1 = getMillisecondsAtBeat(beats[i].param, &beats, i, currentTime, timePerBeat); //it ends at beat beats[i].param holds->push_back(f); break; case BPM_CHANGE: a.timing = currentTime; a.color = beats[i].param; a.type = BPM_CHANGE; a.judgement = UNSET; chart->push_back(a); timePerBeat = BPM_TO_MSEC(beats[i].param); // new tempo! the length of a beat has henceforth and immediately changed break; case SCROLL_STOP: a.timing = currentTime; a.color = beats[i].param; a.type = SCROLL_STOP; chart->push_back(a); currentTime += beats[i].param; // advance the time break; case END_SONG: a.timing = currentTime + 1000; // TODO: something better than this, maybe check the mp3? a.type = END_SONG; chart->push_back(a); break; default: al_trace("IMPOSSIBLE NOTE TYPE IN readDWI() %d\r\n", beats[i].type); } } fclose(fp); // count the maximum score that this chart is worth. it is needed while the chart is being played int maxScore = 0; for ( size_t i = 0; i < chart->size(); i++ ) { if ( chart->at(i).type == TAP || chart->at(i).type == JUMP ) { maxScore += 2; } } maxScore += holds->size()*2; return maxScore; }
DiskImage *di_load_image(char *name) { FILE *file; unsigned int filesize; size_t l, read; DiskImage *di; /* open image */ if (fopen_s(&file, name, "rb") != 0) { return NULL; } /* get file size*/ if (fseek(file, 0, SEEK_END)) { fclose(file); return NULL; } filesize = ftell(file); fseek(file, 0, SEEK_SET); if ((di = malloc(sizeof(*di))) == NULL) { fclose(file); return NULL; } di->size = filesize; /* allocate buffer for image */ if ((di->image = malloc(filesize)) == NULL) { free(di); fclose(file); return NULL; } /* read file into buffer */ read = 0; while (read < filesize) { l = fread(di->image, 1, filesize - read, file); if (l) { read += l; } else { free(di->image); free(di); fclose(file); return NULL; } } fclose(file); di->errinfo = NULL; /* check image type */ switch (filesize) { case D64ERRSIZE: /* D64 with error info */ di->errinfo = &(di->image[D64SIZE]); case D64SIZE: /* standard D64 */ di->type = D64; di->bam.track = 18; di->bam.sector = 0; di->dir = di->bam; break; case D71ERRSIZE: /* D71 with error info */ di->errinfo = &(di->image[D71SIZE]); case D71SIZE: di->type = D71; di->bam.track = 18; di->bam.sector = 0; di->bam2.track = 53; di->bam2.sector = 0; di->dir = di->bam; break; case D81ERRSIZE: /* D81 with error info */ di->errinfo = &(di->image[D81SIZE]); case D81SIZE: di->type = D81; di->bam.track = 40; di->bam.sector = 1; di->bam2.track = 40; di->bam2.sector = 2; di->dir.track = 40; di->dir.sector = 0; break; default: free(di->image); free(di); return NULL; } size_t filenameLen = strlen(name) + 1; if ((di->filename = malloc(filenameLen)) == NULL) { free(di->image); free(di); return NULL; } strcpy_s(di->filename, filenameLen, name); di->openfiles = 0; di->blocksfree = blocks_free(di); di->modified = 0; di->interleave = interleave(di->type); set_status(di, 254, 0, 0); return di; }
void main(int argc, TCHAR *argv[]) { FILE *fd = NULL; // The inputted list of scenarios to examine. HANDLE hd = NULL; // Handle to scenarios. TCHAR szCmdPmtPath[SIZE_256]; TCHAR szCmdPmtInputFileName[SIZE_256]; TCHAR szCmdPmtInputTitleName[SIZE_128]; DWORD pathLength; C3mbStaticsLib staticLib; int numLineConverstions; int lineNumber; int i; BOOL generateNew; BOOL aeOn = FALSE; BOOL deleteOuputFile = FALSE; TCHAR szBuffer[SIZE_256]; TCHAR szLine[SIZE_256]; TCHAR szScenarioFileName[SIZE_128]; TCHAR szSwitch[NUMVALIDSWITCHES][SIZE_16]; double aeDb; BOOL aeCycleOn; //----------------------------------------------------------------------------------// // Print Banner //-------------// printf("3MBS Verfication Application ver %3.1f\n\n", MMMBS_VERFICTN_APP_VER); if(argc < 2) { printf("Missing input file name containing list of scenarios to examine\n\n"); printf("Usage: 3MBSValidation [listfile.txt]\n"); Sleep(5000); return; } strncpy_s(szCmdPmtInputFileName, // Destination buffer TCHARBFLEN(szCmdPmtInputFileName), // Length of the destination bufffer argv[1], // String to be copied TCHARBFLEN(szCmdPmtInputFileName)); // Max count staticLib.GetPathAndFileTitleFromFileName(szCmdPmtInputFileName, // Inputted file name szCmdPmtPath, // Buffer for file path TCHARBFLEN(szCmdPmtPath), // Length of the file path buffer szCmdPmtInputTitleName, // Buffer for file title TCHARBFLEN(szCmdPmtInputTitleName)); // Length of the file title buffer // Set the path if one was specified. Otherwise, get the current directory. if((strlen(szCmdPmtPath) > 0) && (FALSE == SetCurrentDirectory(szCmdPmtPath))) { printf("Invalid path (%s) specified in input: %s\n", szCmdPmtPath, szCmdPmtInputFileName); Sleep(5000); return; } else { pathLength = GetCurrentDirectory(SIZE_256, szCmdPmtPath); if(pathLength == 0 || pathLength > SIZE_256) { printf("Current directory is too deep\n"); Sleep(5000); return; } } printf("Working Directory: %s\n ", szCmdPmtPath); printf("Input File: %s\n", szCmdPmtInputTitleName); fopen_s(&fd, szCmdPmtInputFileName, "r"); if(fd == NULL) { printf("Unable to open file %s\n\n", szCmdPmtInputFileName); return; } // Scan the file. lineNumber = 0; while(NULL != fgets(szLine, SIZE_256, fd)) { // Reset to the current file directory. SetCurrentDirectory(szCmdPmtPath); // Initialize/update variables. lineNumber++; // Skip comments and irrelevant tokens in the text file describing the test cases. if(szLine[0] == '%' || szLine[0] == ' ' || strlen(szLine) <= 1) continue; totalCount++; // A scenario will have, at a minimum, 5 characters (the name plus ".sce"). if(strlen(szLine) < 5) { printf("\"%s\" on line %d is an invalid token, skipping...\n", szLine, lineNumber); skippedCount++; continue; } // Read in the name of the scenario to run and optional switches. memset(szSwitch, 0, NUMVALIDSWITCHES*SIZE_16); numLineConverstions = sscanf_s(szLine, "%s %s %s", szScenarioFileName, szSwitch[0], szSwitch[1], szSwitch[2]); if(numLineConverstions > NUMVALIDSWITCHES+1) { printf("\"%s\" on line %d has too many tokens, skipping...\n", szLine, lineNumber); skippedCount++; continue; } if(szLine[strlen(szLine) - 1] == '\n') szLine[strlen(szLine) - 1] = 0; printf("\n%s \n", szLine); // Verify the extension is correct. staticLib.GetExtension(szScenarioFileName, szBuffer, SIZE_256); if(strcmp(szBuffer, ".sce") != 0) { printf("\"%s\" on line %d has invalid extension, skipping...\n", szScenarioFileName, lineNumber); skippedCount++; continue; } // Default values aeDb = 0.25f; aeCycleOn = FALSE; generateNew = FALSE; aeOn = FALSE; // Determine switches (magic number 3 because at this time there can be only // three switches). for(i=0; i<NUMVALIDSWITCHES && strlen(szSwitch[i]); i++) { if(strcmp(szSwitch[i], "-g") == 0) generateNew = TRUE; else if(strcmp(szSwitch[i], "-a") == 0) aeOn = TRUE; else if(strcmp(szSwitch[i], "-d") == 0) { generateNew = TRUE; deleteOuputFile = TRUE; } else { printf("\"%s\" on line %d has an invalid switch, skipping...\n", szLine, lineNumber); skippedCount++; } } RunScenario(szScenarioFileName, generateNew, aeOn, deleteOuputFile, .001, lineNumber); } fclose(fd); printf("\n"); printf("Summary Results:\n"); printf("Total Files:%d Total Errors:%d\n", totalCount, errorCount); printf("\tGenerate New: %d\n", generateNewCount); printf("\tComparisons: Success:%d Fail:%d Skipped:%d\n", successCount, failCount, skippedCount); }
void CFYSPrintDoc::UnpackFiles() { CString strTemp; CString strSep("\\"); CString strFileName = m_strFYSTempPath + FORYOURSOUL_TXT; FILE* input = NULL; errno_t err = fopen_s(&input, strFileName, "rb"); if (!input || err != 0) { SetError(String("Failed to open %s", strFileName)); return; } HGLOBAL hMemory; BYTE* pMemory; // unpack the mini header hMemory = ::GlobalAlloc(GMEM_MOVEABLE, sizeof(BYTE)); pMemory = (BYTE*)::GlobalLock(hMemory); char xz = ']'; do { fread(pMemory, sizeof(BYTE), 1, input); strTemp += (char)*pMemory; }while((*(char*)pMemory) != xz); ::GlobalUnlock(hMemory); ::GlobalFree(hMemory); // unpack streamheader strTemp = strTemp.Mid(1, strTemp.Find(',', 0)-1); DWORD dwSize = atoi(strTemp); hMemory = ::GlobalAlloc(GMEM_MOVEABLE, dwSize); pMemory = (BYTE*)::GlobalLock(hMemory); fread(pMemory, sizeof(BYTE), dwSize, input); CString strPath = m_strFYSTempPath + XML_PATH + strSep; strTemp.Format("%sXP_%s", strPath, STREAMHDR_XML); FILE* output = NULL; err = fopen_s(&output, strTemp, "wb"); if (!output || err != 0) { SetError(String("Failed to open %s", strTemp)); } else { fwrite(pMemory, sizeof(BYTE), dwSize, output); fclose(output); output = NULL; } ::GlobalUnlock(hMemory); ::GlobalFree(hMemory); // time to read the stream header into a xml class CXMLDocument* pXMLDoc = new CXMLDocument; pXMLDoc->Load(strTemp, false); CString strCount = pXMLDoc->GetStringValue("//FYS_DataStreamHeader//Files", "Count"); int nFileCount = atoi(strCount); for (int i=0, offset=0; i<nFileCount; i++) { CString strSrch = String("//FYS_DataStreamHeader//Files//File[@StartOffset = '%ld']", offset); CString strType = pXMLDoc->GetStringValue(strSrch, "Type"); CString strName = pXMLDoc->GetStringValue(strSrch, "Name"); CString strSize = pXMLDoc->GetStringValue(strSrch, "Size"); DWORD dwSize = atoi(strSize); hMemory = ::GlobalAlloc(GMEM_MOVEABLE, dwSize); pMemory = (BYTE*)::GlobalLock(hMemory); fread(pMemory, sizeof(BYTE), dwSize, input); if (strType == "DataEnvelope") strPath = m_strFYSTempPath + XML_PATH + strSep; if (strType == "Image") strPath = m_strFYSTempPath + IMAGES_PATH + strSep; if (strType == "Font") strPath = m_strFYSTempPath + FONTS_PATH + strSep; strTemp.Format("%sXP_%s", strPath, strName); err = fopen_s(&output, strTemp, "wb"); if (!output || err != 0) { SetError(String("Failed to open %s", strTemp)); } else { fwrite(pMemory, sizeof(BYTE), dwSize, output); fclose(output); output = NULL; } ::GlobalUnlock(hMemory); ::GlobalFree(hMemory); offset += dwSize; } fclose(input); delete pXMLDoc; }
bool CLogger::SaveLogsInFile () { bool isOk = false; FILE *file=NULL; //nombre del archivo std::string l_sPathFile = ""; uint32 day, month, year, hour, minute, second; baseUtils::GetDate(day, month, year, hour, minute, second); baseUtils::FormatSrting(l_sPathFile, "%s_(%d-%d-%d)_(%dh-%dm-%ds).txt", m_sPathFile.c_str(), day, month, year, hour, minute, second); //crea archivo fopen_s(&file,l_sPathFile.c_str(),"w"); std::string report = l_sPathFile; report += "\n"; //rellena el archivo if (file!=NULL) { std::vector<SLog>::const_iterator it = m_vLogs.begin(); std::vector<SLog>::const_iterator itEnd = m_vLogs.end(); for(; it != itEnd; ++it) { //Recorremos todos los logs y vamos rellenando el archivo SLog new_log = *it; std::string number; baseUtils::FormatSrting(l_sPathFile, "%d", new_log.m_uLogLine); report +=number; report += "\t"; switch(new_log.m_eLogLevel) { case ELL_INFORMATION: { report += "[INFORMATION]"; } break; case ELL_WARNING: { report += "[ WARNING ]"; } break; case ELL_ERROR: { report += "[___ERROR___]"; } } report += "\t"; report += new_log.m_sLogText; report += "\n"; } fprintf(file,"%s",report.c_str()); //cierra archivo fclose(file); isOk = true; } if (isOk) { AddNewLog(ELL_INFORMATION,"El log ha sido guardado correctamente en un fichero fisico"); } return isOk; }
UserStream::UserStream(const char* filename, bool load) : fp(NULL) { // Swap these two lines around if you get a compiling error. // fp = fopen(filename, load ? "rb" : "wb"); fopen_s(&fp,filename, load ? "rb" : "wb"); }
bool CFYSPrintDoc::CreateXmlDoc(CString& strOrderId, CString& strCorrId, CString& strFYSInfo, bool bUnpackFiles) { if (!m_pAGDoc) return false; CWaitCursor Wait; Initialize(); if (!CreateDirAndSubDirs()) return false; // Documents element CString strDocFileName; { // strip the last "\" int nLen = m_strFYSTempPath.GetLength(); CString strTempPath = m_strFYSTempPath.Left(nLen-1); strDocFileName = TempFileName(strTempPath, "4YS", "txt"); strDocFileName = m_strFYSTempPath + strDocFileName; FILE* docout = NULL; errno_t err = fopen_s(&docout, strDocFileName, "wb"); if (!docout || err != 0) { SetError(String("Failed to open %s", strDocFileName)); return false; } SIZE PageSize = {0,0}; m_pAGDoc->GetPageSize(PageSize); double dx = DINCHES(PageSize.cx); double dy = DINCHES(PageSize.cy); fprintf(docout, " <Documents Count='1'>\r\n"); fprintf(docout, " <Document CLT_CorrelationID='%s' FYS_CorrelationID='%s'>\r\n", strOrderId, strCorrId); fprintf(docout, " <GreetingCard PageWidth='%0.5G' PageHeight='%0.5G' />\r\n", dx, dy); int nPages = m_pAGDoc->GetNumPages(); for (int nPage = 0; nPage < nPages; nPage++) { CAGPage* pPage = m_pAGDoc->GetPage(nPage); if (!pPage) continue; if (!PageHasSymbols(pPage)) continue; fprintf(docout, "\t\t\t<Page PageNumber='%d'>\r\n", nPage+1); int nLayers = pPage->GetNumLayers(); for (int nLayer = 0; nLayer < nLayers; nLayer++) { CAGLayer* pLayer = pPage->GetLayer(nLayer); if (!pLayer) continue; int nSymbols = pLayer->GetNumSymbols(); for (int nSymbol = nSymbols - 1; nSymbol >= 0; nSymbol--) { bool bRetVal = true; CAGSym* pSym = pLayer->GetSymbol(nSymbol); if (!pSym || pSym->IsHidden()) continue; pSym->RegisterFileSpecsCallback(fnFileSpecs, (LPARAM)this); int idSym = pSym->GetID(); bool bReposition = (idSym == IDR_AGLOGO || idSym == IDR_CARDBACK_COPYRIGHT); if (bReposition) { // Move these symbols up to make room for the FYS logo CAGMatrix Matrix = pSym->GetMatrix(); Matrix.Translate(0, -(INCHES(0.5))); pSym->SetMatrix(Matrix); } pSym->WriteFYSXml(docout, 4); if (bReposition) { CAGMatrix Matrix = pSym->GetMatrix(); Matrix.Translate(0, INCHES(0.5)); pSym->SetMatrix(Matrix); } if (pSym->IsImage()) { CAGSymImage* pSymImage = (CAGSymImage*)pSym; CString strSep("\\"); CString strImagePath = m_strFYSTempPath + IMAGES_PATH + strSep; bRetVal = DumpImageFile(pSymImage, strImagePath); if (bRetVal) { SIZE PageSize; pPage->GetPageSize(PageSize); if (pSymImage->DoCoverDraw() && pSymImage->IsCoverAllowed()) pSymImage->WriteXmlRects(docout, PageSize, 4); } } pSym->UnregisterFileSpecsCallback(); if (!bRetVal) return false; } } fprintf(docout, "\t\t\t</Page>\r\n"); } fprintf(docout, " </Document>\r\n"); fprintf(docout, " </Documents>\r\n"); fclose(docout); } CString strSep("\\"); CString strFontsPath = m_strFYSTempPath + FONTS_PATH + strSep; DumpFontFiles(strFontsPath); // Get Configuration element if (!GetConfigurationElement(strFYSInfo)) { CleanUpEx(strDocFileName); return false; } // Get Resources element if (!GetResourcesElement()) { CleanUpEx(strDocFileName); return false; } // Write CreateAndPrint.xml file CString strXmlPath = m_strFYSTempPath + XML_PATH + strSep; if (!WriteCreatePrintXml(strDocFileName, strXmlPath)) { CleanUpEx(strDocFileName); return false; } // Write StreamHdr.xml file if (!WriteXmlStreamHeader(strXmlPath)) { CleanUp(); return false; } // Write 4YourSoul.txt file if (!CreateSendFile()) { CleanUp(); return false; } if (bUnpackFiles) UnpackFiles(); CleanUp(); return true; }
void GLFontBase::CreateImpl(const char *Filename, bool PixelPerfect) { Font.Char = NULL; FreeResources(); FILE *Input; //Open font file if (fopen_s(&Input, Filename, "rb") != 0) throw GLFontError::InvalidFile(); //Read glFont structure fread(&Font, sizeof(GLFONT), 1, Input); unsigned int tex; //Save texture number glGenTextures(1, &tex); Font.Tex = tex; //Get number of characters //endian_swap(Font.IntEnd); //endian_swap(Font.IntStart); int Num = Font.IntEnd - Font.IntStart + 1; //Allocate memory for characters Font.Char = new GLFONTCHAR[Num]; //Read glFont characters fread(Font.Char, sizeof(GLFONTCHAR), Num, Input); //Get texture size Num = Font.TexWidth * Font.TexHeight * 2; //Allocate memory for texture data char *TexBytes = new char[Num]; //Read texture data fread(TexBytes, sizeof(char), Num, Input); //Set texture attributes glBindTexture(GL_TEXTURE_2D, Font.Tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); if (PixelPerfect) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //Create texture glTexImage2D(GL_TEXTURE_2D, 0, 2, Font.TexWidth, Font.TexHeight, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (void *)TexBytes); //Clean up delete[]TexBytes; fclose(Input); ok = TRUE; }
BOOL WINAPI DllMain(HMODULE hDll, DWORD dwReason, PVOID pvReserved) { if(dwReason == DLL_PROCESS_ATTACH) { OutputDebugString("GeDoSaTo: startup"); // read install location from registry getInstallDirectory(); OutputDebugString("GeDoSaTo: Got install dir"); // don't attach to processes on the blacklist / not on the whitelist if(getUseBlacklist() ? onList(getExeFileName(), "blacklist.txt") : !onList(getExeFileName(), "whitelist.txt")) { OutputDebugString("GeDoSaTo: blacklisted / not whitelisted"); if(getExeFileName() == "GeDoSaToTool") return true; return false; } g_active = true; OutputDebugString("GeDoSaTo: Active"); // initialize log string logFn = format("logs\\%s_%s.log", getExeFileName().c_str(), getTimeString().c_str()); std::replace(logFn.begin(), logFn.end(), ':', '-'); std::replace(logFn.begin(), logFn.end(), ' ', '_'); logFn = getInstalledFileName(logFn); fopen_s(&g_oFile, logFn.c_str(), "w"); if(!g_oFile) OutputDebugString(format("GeDoSaTo: Error opening log fn %s", logFn.c_str()).c_str()); else OutputDebugString(format("GeDoSaTo: Opening log fn %s, handle: %p", logFn.c_str(), g_oFile).c_str()); OutputDebugString("GeDoSaTo: Log file initialized, let that take over"); // startup sdlogtime(-1); SDLOG(-1, "===== start "INTERCEPTOR_NAME" %s = fn: %s\n", GeDoSaToVersion(), getExeFileName().c_str()); SDLOG(-1, "===== installation directory: %s\n", getInstallDirectory().c_str()); // load settings Settings::get().load(); Settings::get().report(); KeyActions::get().load(); KeyActions::get().report(); if(!Settings::get().getPreventSteamOverlay() && Settings::get().getLoadSteamOverlayEarly()) { SDLOG(2, "Attempting to pre-load Steam overlay dll.\n"); LoadLibrary("gameoverlayrenderer.dll"); } if(Settings::get().getLoadD3DEarly()) { SDLOG(2, "Early d3d loading.\n"); auto dllname = getSystemDllName("d3d9.dll"); LoadLibrary(dllname.c_str()); } // detour startDetour(); return true; } if(dwReason == DLL_PROCESS_DETACH && g_active) { Settings::get().shutdown(); endDetour(); SDLOG(-1, "===== end =\n"); fclose(g_oFile); } return false; }
int _tmain(int argc, _TCHAR* argv[]) { if (!strcmp(wtoc(argv[1]), "-help")) { PrintHelp(); system("pause"); return 0; } //char* buffer = ReadFile(L"tempLang.txt"); char* buffer = ReadFile(argv[1]); if (buffer == NULL) { printf("NO FILE!!"); return 1; } int countOfLexem = 0; lex* lexic = Lexer(buffer, &countOfLexem); errno_t err1 = fopen_s(&Fdotty, "E:\\C++\\Derivative\\Derivative\\dumpTree.gv", "w"); fprintf(Fdotty, "graph graphname {"); errno_t err2 = fopen_s(&ftrans, "FileForASM.txt", "w"); for (int i = 0; i < countOfLexem; i++) { printf("lexem number %d :\n" "value <%s>\n" "type <%d>\n" "current pos <%s>\n\n", i, lexic[i].val, lexic[i].type, lexic[i].pos); } Var.vars = new char*[COUNTOFREGISTER]; node* top = GetG0(lexic); if (!top) printf("SYNTAX ERROR!!!\n" "at this symbol %s \n", s->pos); s++; node* funcTop = GetG0(s); node* Main = new node; NODECTOR(Main, "main", T_op, top, funcTop); if (!top) printf("SYNTAX ERROR!!!\n" "at this symbol %s \n", s->pos); int count = 0; PrintTree(Main, &count); FILE* fout = NULL; errno_t err = fopen_s(&fout, "Expression.txt", "w"); Print(Main, fout); DottyTree(Main); int countOfJump = 0, pop = 0, flag = 0; Translate(Main, countOfJump, &pop, flag); //fprintf(ftrans, "end"); //reg regis = {}; fprintf(Fdotty,"}"); fclose(Fdotty); fclose(ftrans); ///////////////////////////////////////////////// //char* FROM = "C:\\Users\\Vladimir\\Documents\\Visual Studio 2013\\Projects\\ENLang\Debug" ///////////////////////////////////////////////// system("E:\\C++\\Graphviz2.38\\bin\\dotty.exe E:\\C++\\Derivative\\Derivative\\dumpTree.gv"); system("pause"); return 0; }
void CJfif::ReadFile(const char* fileName) { fopen_s(&fp, fileName, "rb"); ASSERT(0 != fp); fseek(fp, 0, SEEK_END); int fileLength = ftell(fp); fseek(fp, 0, SEEK_SET); ReadWord(SOI_marker); ReadWord(APP0.marker); ReadWord(APP0.len); ReadByte(APP0.JFIF[0]); ReadByte(APP0.JFIF[1]); ReadByte(APP0.JFIF[2]); ReadByte(APP0.JFIF[3]); ReadByte(APP0.JFIF[4]); ReadWord(APP0.version); ReadByte(APP0.density_unit); ReadWord(APP0.Xdensity); ReadWord(APP0.Ydensity); ReadWord(APP0.thumbnail); JFIF_DQT *dqt[2]; dqt[0] = &DQT_Luma; dqt[1] = &DQT_Chroma; for (int i=0; i<2; i++) { ReadWord(dqt[i]->marker); ReadWord(dqt[i]->len); ReadByte(dqt[i]->id); for (int j=0; j<64; j++) { ReadByte(dqt[i]->data[j]); } } ReadWord(SOF0.marker); ReadWord(SOF0.len); ReadByte(SOF0.precision); ReadWord(SOF0.height); ReadWord(SOF0.width); ReadByte(SOF0.num_comp); ReadByte(SOF0.Y.id); ReadByte(SOF0.Y.sample); ReadByte(SOF0.Y.quant_table_id); ReadByte(SOF0.Cb.id); ReadByte(SOF0.Cb.sample); ReadByte(SOF0.Cb.quant_table_id); ReadByte(SOF0.Cr.id); ReadByte(SOF0.Cr.sample); ReadByte(SOF0.Cr.quant_table_id); JFIF_DHT *dht[4]; dht[0] = &DHT_Luma_dc; dht[1] = &DHT_Chroma_dc; dht[2] = &DHT_Luma_ac; dht[3] = &DHT_Chroma_ac; for (int i=0; i<4; i++) { ReadWord(dht[i]->marker); ReadWord(dht[i]->len); ReadByte(dht[i]->id); for (int j=0; j<16; j++) { ReadByte(dht[i]->bits[j]); } for (int j=0; j<dht[i]->size_var; j++) { ReadByte(dht[i]->var[j]); } } ReadWord(SOS.marker); ReadWord(SOS.len); ReadByte(SOS.num_comp); ReadWord(SOS.luma); ReadWord(SOS.chroma1); ReadWord(SOS.chroma2); ReadByte(SOS.spectral[0]); ReadByte(SOS.spectral[1]); ReadByte(SOS.spectral[2]); int curPos = ftell(fp); data_size = fileLength - curPos - 2; data = new uint8[data_size]; ASSERT(0 != data); for (int i=0; i<data_size; i++) { ReadByte(data[i]); } ReadWord(EOI_marker); fclose(fp); }
SDL_RWops * SDL_RWFromFile(const char *file, const char *mode) { SDL_RWops *rwops = NULL; if (!file || !*file || !mode || !*mode) { SDL_SetError("SDL_RWFromFile(): No file or no mode specified"); return NULL; } #if defined(ANDROID) #ifdef HAVE_STDIO_H /* Try to open the file on the filesystem first */ if (*file == '/') { FILE *fp = fopen(file, mode); if (fp) { return SDL_RWFromFP(fp, 1); } } else { /* Try opening it from internal storage if it's a relative path */ char *path; FILE *fp; path = SDL_stack_alloc(char, PATH_MAX); if (path) { SDL_snprintf(path, PATH_MAX, "%s/%s", SDL_AndroidGetInternalStoragePath(), file); fp = fopen(path, mode); SDL_stack_free(path); if (fp) { return SDL_RWFromFP(fp, 1); } } } #endif /* HAVE_STDIO_H */ /* Try to open the file from the asset system */ rwops = SDL_AllocRW(); if (!rwops) return NULL; /* SDL_SetError already setup by SDL_AllocRW() */ if (Android_JNI_FileOpen(rwops, file, mode) < 0) { SDL_FreeRW(rwops); return NULL; } rwops->size = Android_JNI_FileSize; rwops->seek = Android_JNI_FileSeek; rwops->read = Android_JNI_FileRead; rwops->write = Android_JNI_FileWrite; rwops->close = Android_JNI_FileClose; rwops->type = SDL_RWOPS_JNIFILE; #elif defined(__WIN32__) rwops = SDL_AllocRW(); if (!rwops) return NULL; /* SDL_SetError already setup by SDL_AllocRW() */ if (windows_file_open(rwops, file, mode) < 0) { SDL_FreeRW(rwops); return NULL; } rwops->size = windows_file_size; rwops->seek = windows_file_seek; rwops->read = windows_file_read; rwops->write = windows_file_write; rwops->close = windows_file_close; rwops->type = SDL_RWOPS_WINFILE; #elif HAVE_STDIO_H { #ifdef __APPLE__ FILE *fp = SDL_OpenFPFromBundleOrFallback(file, mode); #elif __WINRT__ FILE *fp = NULL; fopen_s(&fp, file, mode); #else FILE *fp = fopen(file, mode); #endif if (fp == NULL) { SDL_SetError("Couldn't open %s", file); } else { rwops = SDL_RWFromFP(fp, 1); } } #else SDL_SetError("SDL not compiled with stdio support"); #endif /* !HAVE_STDIO_H */ return rwops; }
int _tmain(int argc, _TCHAR* argv[]) { char* szSourceSring = QRCODE_TEXT; unsigned int unWidth, x, y, l, n, unWidthAdjusted, unDataBytes; unsigned char* pRGBData, *pSourceData, *pDestData; QRcode* pQRC; FILE* f; /* * Create a symbol from the string. The library automatically parses the input * string and encodes in a QR Code symbol. * @warning This function is THREAD UNSAFE when pthread is disabled. * @param string input string. It must be NUL terminated. * @param version version of the symbol. If 0, the library chooses the minimum * version for the given input data. * @param level error correction level. * @param hint tell the library how non-alphanumerical characters should be * encoded. If QR_MODE_KANJI is given, kanji characters will be * encoded as Shif-JIS characters. If QR_MODE_8 is given, all of * non-alphanumerical characters will be encoded as is. If you want * to embed UTF-8 string, choose this. * @param casesensitive case-sensitive(1) or not(0). * @return an instance of QRcode class. The version of the result QRcode may * be larger than the designated version. On error, NULL is returned, * and errno is set to indicate the error. See Exceptions for the * details. * @throw EINVAL invalid input object. * @throw ENOMEM unable to allocate memory for input objects. * @throw ERANGE input data is too large. */ // Compute QRCode if (pQRC = QRcode_encodeString(szSourceSring, 0, QR_ECLEVEL_H, QR_MODE_8, 1)) { unWidth = pQRC->width; unWidthAdjusted = unWidth * OUT_FILE_PIXEL_PRESCALER * 3; if (unWidthAdjusted % 4) unWidthAdjusted = (unWidthAdjusted / 4 + 1) * 4; unDataBytes = unWidthAdjusted * unWidth * OUT_FILE_PIXEL_PRESCALER; // Allocate pixels buffer if (!(pRGBData = (unsigned char*)malloc(unDataBytes))) { printf("Out of memory"); exit(-1); } // Preset to white memset(pRGBData, 0xff, unDataBytes); // Prepare bmp headers BITMAPFILEHEADER kFileHeader; kFileHeader.bfType = 0x4d42; // "BM" kFileHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + unDataBytes; kFileHeader.bfReserved1 = 0; kFileHeader.bfReserved2 = 0; kFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); BITMAPINFOHEADER kInfoHeader; kInfoHeader.biSize = sizeof(BITMAPINFOHEADER); kInfoHeader.biWidth = unWidth * OUT_FILE_PIXEL_PRESCALER; kInfoHeader.biHeight = -((int)unWidth * OUT_FILE_PIXEL_PRESCALER); kInfoHeader.biPlanes = 1; kInfoHeader.biBitCount = 24; kInfoHeader.biCompression = BI_RGB; kInfoHeader.biSizeImage = 0; kInfoHeader.biXPelsPerMeter = 0; kInfoHeader.biYPelsPerMeter = 0; kInfoHeader.biClrUsed = 0; kInfoHeader.biClrImportant = 0; // Convert QrCode bits to bmp pixels pSourceData = pQRC->data; for(y = 0; y < unWidth; y++) { pDestData = pRGBData + unWidthAdjusted * y * OUT_FILE_PIXEL_PRESCALER; for(x = 0; x < unWidth; x++) { if (*pSourceData & 1) { for(l = 0; l < OUT_FILE_PIXEL_PRESCALER; l++) { for(n = 0; n < OUT_FILE_PIXEL_PRESCALER; n++) { *(pDestData + n * 3 + unWidthAdjusted * l) = PIXEL_COLOR_B; *(pDestData + 1 + n * 3 + unWidthAdjusted * l) = PIXEL_COLOR_G; *(pDestData + 2 + n * 3 + unWidthAdjusted * l) = PIXEL_COLOR_R; } } } pDestData += 3 * OUT_FILE_PIXEL_PRESCALER; pSourceData++; } } // Output the bmp file if (!(fopen_s(&f, OUT_FILE, "wb"))) { fwrite(&kFileHeader, sizeof(BITMAPFILEHEADER), 1, f); fwrite(&kInfoHeader, sizeof(BITMAPINFOHEADER), 1, f); fwrite(pRGBData, sizeof(unsigned char), unDataBytes, f); fclose(f); } else { printf("Unable to open file"); exit(-1); } // Free data free(pRGBData); QRcode_free(pQRC); } else { printf("NULL returned"); exit(-1); } return 0; }
/** @brief */ int __xLog( int type, LPCTSTR str, ...) { XCheckRecursive checkRecursive; if( checkRecursive.IsRecursive() ) return 1; TCHAR szBuff[1024]; // utf8이 길어서 넉넉하게 잡았다. va_list vl; va_start(vl, str); _vstprintf_s(szBuff, str, vl); va_end(vl); #ifdef _DEBUG #else // 릴리즈 모드에선 로그나 에러모두 파일에 써야 한다 { char szChar[8192]; memset( szChar, 0, sizeof(szChar) ); WideCharToMultiByte(CP_ACP, 0, szBuff, -1, szChar, 1024, NULL, NULL); int len = strlen(szChar); szChar[len] = '\n'; szChar[len+1] = 0; FILE *fp; #ifdef _XTOOL CString str = XE::GetCwd(); str += "error.txt"; fopen_s( &fp, Convert_TCHAR_To_char( str ), "a+" ); #else fopen_s( &fp, "error.txt", "a+" ); #endif //XBREAK( fp == NULL ); if( XASSERT(fp) ) { xPutsTimeString( fp ); fputs( szChar, fp ); int size = ftell( fp ); fclose(fp); } #ifdef _GAME // 게임에서만... // 로그파일이 무한정 쌓이지 않도록 한다. if( size >= 0xffff ) { fopen_s( &fp, "error.txt", "w+" ); if( fp ) { xPutsTimeString( fp ); fputs( szChar, fp ); fclose( fp ); #ifndef _MASTER // 마스터본이 아닐때만 XALERT( "로그파일 삭제" ); #endif } } #endif } #endif TCHAR szTitle[256] = {0,}; if( type == XLOGTYPE_ERROR ) { _tcscpy_s( szTitle, _T("Error!") ); // ::OutputDebugString( szBuff ); // TRACE로 한글출력이 안되서 이걸로 바꿈 #ifdef _XTOOL AfxDebugBreak(); AfxMessageBox( szBuff, MB_OK ); // 툴에선 XERROR를 불러도 exit()시키지 않는다. 데이터를 저장하지 않은상태이기때문에 어떻게 해서든 살리려고 시도해야한다 #else // ::MessageBox( NULL, szBuff, szTitle, MB_OK ); AfxMessageBox( szBuff, MB_OK ); AfxDebugBreak(); exit(1); #endif } else if( type == XLOGTYPE_LOG ) { // LOG _tcscpy_s( szTitle, _T("Message!") ); _tcscat_s( szBuff, _T("\n") ); // ::OutputDebugString( szBuff ); // TRACE로 한글출력이 안되서 이걸로 바꿈 } else if( type == XLOGTYPE_ALERT ) { AfxDebugBreak(); _tcscpy_s( szTitle, _T("Message!") ); // ::OutputDebugString( szBuff ); // TRACE로 한글출력이 안되서 이걸로 바꿈 #ifdef _XTOOL AfxMessageBox( szBuff, MB_OK ); #else // int retv = ::MessageBox( NULL, szBuff, szTitle, MB_OK ); AfxMessageBox( szBuff, MB_OK ); #endif } #ifdef _XCONSOLE CONSOLE( "%s", szBuff ); // 툴에서는 콘솔뷰로도 보낸다 #endif return 1; // XBREAK()같은데서 쓰이므로 항상 1을 리턴해야함 }
int main(int argc, char **argv) { char vbuf[4096] = { 0 }; char *version, *ncommits, *sha; FILE *po; int buflen; fprintf(stderr, "Starting CreateVersion\n"); if (argc != 2) { fprintf(stderr, "Usage: %s <Outputfile>\n", argv[0]); exit(-1); } /** Get the output */ po = popen("git describe --long --match v*", "r"); if (!po) { perror("git describe"); exit(-2); } if (!fgets(vbuf, sizeof(vbuf), po)) { fprintf(stderr, "git describe closed stream\n"); exit(-3); } pclose(po); buflen = (int)strlen(vbuf); vbuf[buflen - 2] = '\0'; buflen -= 1; // SHA1 (Remove the leading 'g') find_delim(vbuf, &sha, &buflen); sha++; // Commit # - Will be used as build number find_delim(vbuf, &ncommits, &buflen); // Version version = vbuf; // Break the version number into its components unsigned int major=0, mid=0, minor=0; int nFields = sscanf_s(version, "v%u.%u.%u",&major, &mid, &minor) ; if (nFields != 3) { fprintf(stderr, "Version string corrupt\n"); exit(-4); } // Open output file char * filename = argv[1]; if (!filename) { fprintf(stderr, "Bad output file name\n"); exit(-5); } FILE * f; errno_t err = fopen_s(&f, filename, "w+"); if (err || !f) { fprintf(stderr, "Could not oupen output file name (errno=%d)\n", err); exit(-6); } // Put data into file fprintf(f, "#pragma once\n"); fprintf(f, "#define VER_H_ %u\n", major); fprintf(f, "#define VER_M_ %u\n", mid); fprintf(f, "#define VER_L_ %u\n", minor); fprintf(f, "#define BUILD %s\n", ncommits); fprintf(f, "\n"); fprintf(f, "#define FILEVER\t\t\t\t\"%u, %u, %u, %s\"\n", major, mid, minor, ncommits); fprintf(f, "#define PRODVER_TAG\t\t\t\"%s\"\n", version); fprintf(f, "#define PRODVER_SHA1\t\t\"%s\"\n", sha); fprintf(f, "\n"); return 0; }
byte* HttpResponse::GetStaticContent2(const char *file_name, long *len) { FILE *fp; char *buf = NULL; DWORD res = ::WaitForSingleObject(ghMutex, 10000); if (res == WAIT_OBJECT_0) { char* fname = _strdup(file_name); if (cacheController->FindTemplate(fname)) { string mcontent = cacheController->GetTemplateContent(fname); byte* result = (byte*)mcontent.c_str(); return result; } else { cacheController->AddTemplate(fname, fname); string mcontent = cacheController->GetTemplateContent(fname); byte* result = (byte*)mcontent.c_str(); return result; } /* time_t now = time(0); ibuflist_t itr; for (itr = m_bufferList.begin(); itr != m_bufferList.end(); itr++) { lpstatic_content_t pitem = *itr; int diff = strcmp(pitem->name, file_name); if (diff == 0) { pitem->rawtime = time(0); ::ReleaseMutex(ghMutex); return pitem->content; } double dt = difftime(now, pitem->rawtime); } */ fopen_s(&fp, file_name, "rb"); assert(fp != NULL); //if (fp == NULL) //{ // return NULL; //} fseek(fp, 0, SEEK_END); long size = ftell(fp); *len = size; rewind(fp); buf = (char*)malloc(size + 1); assert(buf != NULL); memset(buf, 0, size); int i = 0; int ch; while ((ch = fgetc(fp)) != EOF) { buf[i++] = ch; } fclose(fp); /* lpstatic_content_t p1 = (lpstatic_content_t)malloc(sizeof(static_content_t)); p1->name = _strdup(file_name); p1->content = buf; p1->rawtime = time(0); m_bufferList.push_back(p1); */ } ::ReleaseMutex(ghMutex); return (byte*)buf; }
static void conf_zonefiles_parse_thread(void *v) { struct XParseThread *p = (struct XParseThread *)v; struct Catalog *db = p->db_load; struct Configuration *cfg = p->cfg; struct ZoneFileParser *parser; static const struct DomainPointer root = {(const unsigned char*)"\0",1}; size_t directory_index; size_t file_index; size_t current_index; fflush(stderr); fflush(stdout); /* * Start the parsing */ parser = zonefile_begin( root, 60, 128, cfg->options.directory, zonefile_load, db, cfg->insertion_threads ); /* * Find the starting point. This converts the single * integer number into a [directory, file] index pair. */ current_index = 0; for (directory_index = 0; directory_index < cfg->zonedirs_length; directory_index++) { struct Cfg_ZoneDir *zonedir = cfg->zonedirs[directory_index]; current_index += zonedir->file_count; if (current_index >= p->start_index) break; } file_index = current_index - p->start_index; /* * 'for all zonefiles in this directory...' */ if (directory_index < cfg->zonedirs_length) while (current_index < p->end_index) { const char *filename; FILE *fp; int err; uint64_t filesize; struct Cfg_ZoneDir *zonedir; /* If we've gone past the end of this directory, * then start parsing the next directory */ zonedir = cfg->zonedirs[directory_index]; if (file_index >= zonedir->file_count) { file_index = 0; directory_index++; if (directory_index >= cfg->zonedirs_length) break; zonedir = cfg->zonedirs[directory_index]; } filename = zonedir->files[file_index].filename; filesize = zonedir->files[file_index].size; current_index++; file_index++; /* * Open the file */ fflush(stdout); fflush(stderr); err = fopen_s(&fp, filename, "rb"); if (err || fp == NULL) { perror(filename); p->status = Failure; return; } p->total_bytes += filesize; /* * Set parameters */ zonefile_begin_again( parser, root, /* . domain origin */ 60, /* one minute ttl */ filesize, filename); /* * Continue parsing the file until end, reporting progress as we * go along */ for (;;) { unsigned char buf[65536]; size_t bytes_read; bytes_read = fread((char*)buf, 1, sizeof(buf), fp); if (bytes_read == 0) break; zonefile_parse( parser, buf, bytes_read ); } fclose(fp); } /* We are done parsing the directories. Now let's parse * the individual zonefiles */ while (current_index < p->end_index) { const char *filename; FILE *fp; int err; uint64_t filesize; struct Cfg_Zone *zone; if (file_index >= cfg->zones_length) break; zone = cfg->zones[file_index]; filename = zone->file; filesize = zone->file_size; current_index++; file_index++; /* * Open the file */ fflush(stdout); fflush(stderr); err = fopen_s(&fp, filename, "rb"); if (err || fp == NULL) { perror(filename); p->status = Failure; return; } p->total_bytes += filesize; /* * Set parameters */ zonefile_begin_again( parser, root, /* . domain origin */ 60, /* one minute ttl */ filesize, filename); /* * Continue parsing the file until end, reporting progress as we * go along */ for (;;) { unsigned char buf[65536]; size_t bytes_read; bytes_read = fread((char*)buf, 1, sizeof(buf), fp); if (bytes_read == 0) break; zonefile_parse( parser, buf, bytes_read ); } fclose(fp); } if (zonefile_end(parser) == Success) { p->status = Success; } else { fprintf(stderr, "%s: failure\n", ""); p->status = Failure; } }
void X_MODEL::Load(const char* FileName) { FILE *fp = NULL; fopen_s(&fp, FileName, "r"); assert(fp != NULL); char buf[256]; fseek(fp, SEEK_SET, 0); while (!feof(fp)) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "template") == 0) { while (strcmp(buf, "}") != 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); } } if (strcmp(buf, "Frame") == 0) { NODE t_node; m_nodeArray.push_back(t_node); fscanf_s(fp, "%s", buf, sizeof(buf)); m_nodeArray[m_nodeArray.size() - 1].nodeName = buf; fscanf_s(fp, "%*1s"); fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "FrameTransformMatrix") == 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "{") == -1) { fscanf_s(fp, "%*1s"); } float mat[16]; for (int i = 0; i < 16; ++i) { fscanf_s(fp, "%f", &mat[i], sizeof(mat[i])); fscanf_s(fp, "%*1s"); } fscanf_s(fp, "%*1s"); for (int i = 0; i < 4; ++i) { for (int k = 0; k < 4; ++k) { m_nodeArray[m_nodeArray.size() - 1].nodeMat[i][k] = mat[k + (i * 4)]; } } } } if (strcmp(buf, "Mesh") == 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "{") == -1) { fscanf_s(fp, "%*1s"); } unsigned int nVertics; fscanf_s(fp, "%u", &nVertics, sizeof(nVertics)); fscanf_s(fp, "%s", buf, sizeof(buf)); for (int count = 0; count < nVertics; ++count) { float vertices[3]; for (int i = 0; i < 3; ++i) { fscanf_s(fp, "%f", &vertices[i], sizeof(vertices[i])); fscanf_s(fp, "%*1s"); }; fscanf_s(fp, "%*1s"); VERTEX vtx; vtx.x = vertices[0]; vtx.y = vertices[1]; vtx.z = vertices[2]; m_nodeArray[m_nodeArray.size() - 1].vertexArray.push_back(vtx); } // unsigned int nIndicies; fscanf_s(fp, "%u", &nIndicies, sizeof(nIndicies)); fscanf_s(fp, "%1s", buf, sizeof(buf)); for (int count = 0; count < nIndicies; ++count) { int indices; fscanf_s(fp, "%2s", buf, sizeof(buf)); for (int i = 0; i < 3; ++i) { fscanf_s(fp, "%d", &indices, sizeof(indices)); fscanf_s(fp, "%1s", buf, sizeof(buf)); m_nodeArray[m_nodeArray.size() - 1].indexArray.push_back(indices); }; fscanf_s(fp, "%1s", buf, sizeof(buf)); } } else if (strcmp(buf, "MeshNormals") == 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "{") == -1) { fscanf_s(fp, "%*1s"); } unsigned int nNormals; fscanf_s(fp, "%u", &nNormals, sizeof(nNormals)); fscanf_s(fp, "%*1s"); for (int count = 0; count < nNormals; ++count) { float normals[3]; for (int i = 0; i < 3; ++i) { fscanf_s(fp, "%f", &normals[i], sizeof(normals[i])); fscanf_s(fp, "%*1s"); }; fscanf_s(fp, "%*1s"); NORMAL nor; nor.x = normals[0]; nor.y = normals[1]; nor.z = normals[2]; m_nodeArray[m_nodeArray.size() - 1].normalArray.push_back(nor); } } else if (strcmp(buf, "MeshTextureCoords") == 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "{") == -1) { fscanf_s(fp, "%*1s"); } unsigned int nTexCoords; fscanf_s(fp, "%u", &nTexCoords, sizeof(nTexCoords)); fscanf_s(fp, "%*1s"); for (int count = 0; count < nTexCoords; ++count) { float texcoords[2]; for (int i = 0; i < 2; ++i) { fscanf_s(fp, "%f", &texcoords[i], sizeof(texcoords[i])); fscanf_s(fp, "%*1s"); }; fscanf_s(fp, "%*1s"); TEXCOORD tex; tex.u = texcoords[0]; tex.v = texcoords[1]; m_nodeArray[m_nodeArray.size() - 1].texcoordArray.push_back(tex); } } else if (strcmp(buf, "Material") == 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "{") == -1) { fscanf_s(fp, "%*1s"); } float diffuse[4]; for (int i = 0; i < 4; ++i) { fscanf_s(fp, "%f", &diffuse[i], sizeof(diffuse[i])); fscanf_s(fp, "%*1s"); }; fscanf_s(fp, "%*1s"); MATERIAL material; material.diffuse.x = diffuse[0]; material.diffuse.y = diffuse[1]; material.diffuse.z = diffuse[2]; material.diffuse.w = diffuse[3]; //shinness float shinness; fscanf_s(fp, "%f", &shinness, sizeof(shinness)); fscanf_s(fp, "%*1s"); material.shininess = shinness; //specular float specular[3]; for (int i = 0; i < 3; ++i) { fscanf_s(fp, "%f", &specular[i], sizeof(specular[i])); fscanf_s(fp, "%*1s"); }; fscanf_s(fp, "%*1s"); material.specular.x = specular[0]; material.specular.y = specular[1]; material.specular.z = specular[2]; //ambient float ambient[3]; for (int i = 0; i < 3; ++i) { fscanf_s(fp, "%f", &ambient[i], sizeof(ambient[i])); fscanf_s(fp, "%*1s"); }; fscanf_s(fp, "%*1s"); material.ambient.x = ambient[0]; material.ambient.y = ambient[1]; material.ambient.z = ambient[2]; fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "TextureFilename") == 0) { fscanf_s(fp, "%s", buf, sizeof(buf)); if (strcmp(buf, "{") == -1) { fscanf_s(fp, "%*1s"); } fscanf_s(fp, "%s", buf, sizeof(buf)); //material.FileName = buf; //std::string str = material.FileName; std::string str = buf; material.texFileName = str.substr(str.find_first_of('\"', 0) + 1, str.find_last_of('\"', 255) - 1); printf("Load Filename : %s\n", material.texFileName.c_str()); TEXTURE tex; m_nodeArray[m_nodeArray.size() - 1].textureArray.push_back(tex); m_nodeArray[m_nodeArray.size() - 1].textureArray[m_nodeArray[m_nodeArray.size() - 1].textureArray.size() - 1] = TEXTURE(material.texFileName.c_str()); material.texNo = m_nodeArray[m_nodeArray.size() - 1].textureArray.size(); GLuint addID; m_nodeArray[m_nodeArray.size() - 1].texID.push_back(addID); glGenTextures(1, (GLuint*) &m_nodeArray[m_nodeArray.size() - 1].texID[m_nodeArray[m_nodeArray.size() - 1].textureArray.size() - 1]); glBindTexture(GL_TEXTURE_2D, m_nodeArray[m_nodeArray.size() - 1].texID[m_nodeArray[m_nodeArray.size() - 1].textureArray.size() - 1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glEnable(GL_TEXTURE_2D); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_nodeArray[m_nodeArray.size() - 1].textureArray[m_nodeArray[m_nodeArray.size() - 1].textureArray.size() - 1].Width, m_nodeArray[m_nodeArray.size() - 1].textureArray[m_nodeArray[m_nodeArray.size() - 1].textureArray.size() - 1].Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_nodeArray[m_nodeArray.size() - 1].textureArray[m_nodeArray[m_nodeArray.size() - 1].textureArray.size() - 1].image); glDisable(GL_TEXTURE_2D); } fscanf_s(fp, "%*1s"); fscanf_s(fp, "%*1s"); m_nodeArray[m_nodeArray.size() - 1].materialArray.push_back(material); } //Animation //else if (strcmp(buf, "Animation") == 0) { // fscanf_s(fp, "%*1s"); // fscanf_s(fp, "%s", buf, sizeof(buf)); // if(strcmp(buf, "AnimationKey")){ // unsigned int keyType; // fscanf_s(fp, "%u", &keyType, sizeof(keyType)); // if(keyType == 0){//Rotate // } // else if(keyType == 1){//Scale // } // else if(keyType == 2){//Translate // } // else if (keyType == 3) {//matrix // } // } //} } fclose(fp); }
int main(int argc, const char *argv[]) { const char *in_path; FILE *in_file = NULL; FILE *out_file = NULL; const char *nmspace = "GL"; const char *filename; char variable[1024]; size_t i; int num_bytes = 0; int column = 0; const int bytes_per_column = 12; if (argc != 3) { fprintf(stderr, "Invalid args\n"); return 1; } in_path = argv[1]; #ifdef _WIN32 (void)fopen_s(&in_file, in_path, "rb"); #else in_file = fopen(in_path, "rb"); #endif if (!in_file) { fprintf(stderr, "Can't open input file %s\n", in_path); return 1; } #ifdef _WIN32 (void)fopen_s(&out_file, argv[2], "wb"); #else out_file = fopen(argv[2], "wb"); #endif if (!out_file) { fprintf(stderr, "Can't open output file %s\n", argv[2]); fclose(in_file); return 1; } filename = strrchr(in_path, '/'); if (filename) { memcpy(variable, filename + 1, strlen(filename + 1) + 1); } else { memcpy(variable, in_path, strlen(in_path) + 1); } for (i = 0; i < strlen(variable); ++i) { if (variable[i] == '.') { variable[i] = '_'; } } fprintf(out_file, "#include \"GLResources.h\"\n"); fprintf(out_file, "unsigned char %s::%s[] = {\n", nmspace, variable); for (;;) { int ch = fgetc(in_file); if (ch == EOF) { if (feof(in_file)) { fprintf(out_file, "\n"); } break; } if (column == 0) { fprintf(out_file, " "); } fprintf(out_file, "0x%02x, ", ch); ++column; if (column == bytes_per_column) { column = 0; fprintf(out_file, "\n"); } ++num_bytes; } fprintf(out_file, "};\n"); fprintf(out_file, "unsigned int %s::%s_len = %d;\n", nmspace, variable, num_bytes); fclose(out_file); fclose(in_file); return 0; }
void write_putty_version(char *path) { BOOL ret; FILE *fp; char *keywords[] = { //"AppVerName", "AppVersion", "VersionInfoTextVersion", NULL, }; int i; char filename[MAX_PATH * 2], buf[64]; char revision[64] = {0}; char header_line[64]= {0}, *p; // PuTTYのバージョンを取得する。 _snprintf_s(filename, sizeof(filename), _TRUNCATE, "%s%s", path, "\\libs\\putty\\windows\\putty.iss"); if (fopen_s(&fp, filename, "r") != 0) { goto write; } while(!feof(fp)){ char tmp[64]; fgets(buf, sizeof(buf), fp); for (i = 0 ; keywords[i] ; i++) { _snprintf_s(tmp, sizeof(tmp), _TRUNCATE, "%s%s", keywords[i], "=%[^\n]s"); ret = sscanf_s(buf, tmp, revision, sizeof(revision)); if (ret != 1) continue; printf("%s\n", revision); goto close; } } close: fclose(fp); _snprintf_s(filename, sizeof(filename), _TRUNCATE, "%s%s", path, "\\ttssh2\\ttxssh\\puttyversion.h"); // バージョンをチェックし、変更がなければ抜ける if (fopen_s(&fp, filename, "r") != 0) { goto write; } memset(header_line, 0, sizeof(header_line)); if (fread(header_line, sizeof(char), sizeof(header_line)-1, fp) == 0) { fclose(fp); goto write; } if ( (p = strchr(header_line, '"')) == NULL ) { fclose(fp); goto write; } p++; if (strncmp(p, revision, strlen(p)-2) == 0) { fclose(fp); goto end; } fclose(fp); write: _snprintf_s(filename, sizeof(filename), _TRUNCATE, "%s%s", path, "\\ttssh2\\ttxssh\\puttyversion.h"); // バージョンをヘッダに書き込む。 if (fopen_s(&fp, filename, "w+") != 0) { goto end; } if (revision[0] != '\0') { fprintf(fp, "#define PUTTYVERSION \"%s\"\n", revision); } else { fprintf(fp, "#undef PUTTYVERSION\n"); } fclose(fp); end:; }
bool TerrainClass::LoadHeightMap(char* filename) { FILE* filePtr; int error; unsigned int count; BITMAPFILEHEADER bitmapFileHeader; BITMAPINFOHEADER bitmapInfoHeader; int imageSize, i, j, k, index; unsigned char* bitmapImage; unsigned char height; // Open the height map file in binary. error = fopen_s(&filePtr, filename, "rb"); if(error != 0) { return false; } // Read in the file header. count = fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr); if(count != 1) { return false; } // Read in the bitmap info header. count = fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr); if(count != 1) { return false; } // Save the dimensions of the terrain. m_terrainWidth = bitmapInfoHeader.biWidth; m_terrainHeight = bitmapInfoHeader.biHeight; // Calculate the size of the bitmap image data. imageSize = m_terrainWidth * m_terrainHeight * 3; // Allocate memory for the bitmap image data. bitmapImage = new unsigned char[imageSize]; if(!bitmapImage) { return false; } // Move to the beginning of the bitmap data. fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET); // Read in the bitmap image data. count = fread(bitmapImage, 1, imageSize, filePtr); if(count != imageSize) { return false; } // Close the file. error = fclose(filePtr); if(error != 0) { return false; } // Create the structure to hold the height map data. m_heightMap = new HeightMapType[m_terrainWidth * m_terrainHeight]; if(!m_heightMap) { return false; } // Initialize the position in the image data buffer. k=0; // Read the image data into the height map. for(j=0; j<m_terrainHeight; j++) { for(i=0; i<m_terrainWidth; i++) { height = bitmapImage[k]; index = (m_terrainHeight * j) + i; m_heightMap[index].x = (float)i; m_heightMap[index].y = (float)height; m_heightMap[index].z = (float)j; k+=3; } } // Release the bitmap image data. delete [] bitmapImage; bitmapImage = 0; return true; }
/** \brief parse the given file command */ void ParserSingleInstance::parse(const char *command) { size_t len = strlen(command); yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 1; #ifdef _MSC_VER char szFile[MAX_PATH]; char* pstTmpDIr = getTMPDIR(); os_sprintf(szFile, "%s\\%s", pstTmpDIr, "command.temp"); FREE(pstTmpDIr); if (fileLocker) { fclose(fileLocker); } errno_t err; err = fopen_s(&yyin, szFile, "w"); if (err) { ParserSingleInstance::setExitStatus(Parser::Failed); ParserSingleInstance::resetErrorMessage(); wchar_t szError[bsiz]; wchar_t* wszFile = to_wide_string(szFile); os_swprintf(szError, bsiz, _W("%ls: Cannot open file %ls.\n").c_str(), L"parser", wszFile); FREE(wszFile); appendErrorMessage(szError); return; } fwrite(command, sizeof(char), len, yyin); fclose(yyin); fopen_s(&yyin, szFile, "r"); #endif #ifdef __APPLE__ char szFile[PATH_MAX]; char* pstTmpDIr = "/tmp"; sprintf(szFile, "%s/%s", getTMPDIR(), "command.temp"); //FREE(pstTmpDIr); if (fileLocker) { fclose(fileLocker); } yyin = fopen(szFile, "w"); fwrite(command, 1, len, yyin); fclose(yyin); yyin = fopen(szFile, "r"); #endif #ifndef _MSC_VER #ifndef __APPLE__ yyin = fmemopen((void*)command, len, "r"); #endif #endif ParserSingleInstance::disableStrictMode(); ParserSingleInstance::setFileName(L"prompt"); ParserSingleInstance::setTree(nullptr); ParserSingleInstance::setExitStatus(Parser::Succeded); ParserSingleInstance::resetControlStatus(); ParserSingleInstance::resetErrorMessage(); yyparse(); fclose(yyin); #ifdef _MSC_VER DeleteFileA(szFile); #endif #ifdef _MSC_VER //reopen a file to prevents max file opened. fopen_s(&fileLocker, szFile, "w"); #endif #ifdef __APPLE__ fileLocker = fopen(szFile, "w"); #endif }
bool processResourceFile(const QStringList &filenamesIn, const QString &filenameOut, bool list) { if (verbose) fprintf(stderr, "Qt resource compiler\n"); //setup RCCResourceLibrary library; library.setFormat(writeBinary ? RCCResourceLibrary::Binary : RCCResourceLibrary::C_Code); library.setInputFiles(filenamesIn); library.setInitName(initName); library.setVerbose(verbose); library.setCompressLevel(compressLevel); library.setCompressThreshold(compressThreshold); library.setResourceRoot(resourceRoot); if(!library.readFiles(list)) return false; //open output FILE *out_fd = stdout; if (!filenameOut.isEmpty() && filenameOut != QLatin1String("-")) { #if defined(_MSC_VER) && _MSC_VER >= 1400 if (fopen_s(&out_fd, filenameOut.toLocal8Bit().constData(), writeBinary ? "wb": "w")) { #else if(!(out_fd = fopen(filenameOut.toLocal8Bit().constData(), writeBinary ? "wb": "w"))) { #endif fprintf(stderr, "Unable to open %s for writing\n", qPrintable(filenameOut)); return false; } } //do the task bool ret = true; if(list) { const QStringList data = library.dataFiles(); for(int i = 0; i < data.size(); ++i) fprintf(out_fd, "%s\n", qPrintable(QDir::cleanPath(data.at(i)))); } else { ret = library.output(out_fd); } if(out_fd != stdout) fclose(out_fd); //done return ret; } int showHelp(const QString &argv0, const QString &error) { fprintf(stderr, "Qt resource compiler\n"); if (!error.isEmpty()) fprintf(stderr, "%s: %s\n", argv0.toLocal8Bit().constData(), error.toLocal8Bit().constData()); fprintf(stderr, "Usage: %s [options] <inputs>\n\n" "Options:\n" " -o file write output to file rather than stdout\n" " -name name create an external initialization function with name\n" " -threshold level threshold to consider compressing files\n" " -compress level compress input files by level\n" " -root path prefix resource access path with root path\n" " -no-compress disable all compression\n" " -binary output a binary file for use as a dynamic resource\n" " -version display version\n" " -help display this information\n", argv0.toLocal8Bit().constData()); return 1; }
void CJfif::WriteFile(const char* fileName) { fopen_s(&fp, fileName, "wb"); ASSERT(0 != fp); WriteWord(SOI_marker); WriteWord(APP0.marker); WriteWord(APP0.len); WriteByte(APP0.JFIF[0]); WriteByte(APP0.JFIF[1]); WriteByte(APP0.JFIF[2]); WriteByte(APP0.JFIF[3]); WriteByte(APP0.JFIF[4]); WriteWord(APP0.version); WriteByte(APP0.density_unit); WriteWord(APP0.Xdensity); WriteWord(APP0.Ydensity); WriteWord(APP0.thumbnail); JFIF_DQT *dqt[2]; dqt[0] = &DQT_Luma; dqt[1] = &DQT_Chroma; for (int i=0; i<2; i++) { WriteWord(dqt[i]->marker); WriteWord(dqt[i]->len); WriteByte(dqt[i]->id); for (int j=0; j<64; j++) { WriteByte(dqt[i]->data[j]); } } WriteWord(SOF0.marker); WriteWord(SOF0.len); WriteByte(SOF0.precision); WriteWord(SOF0.height); WriteWord(SOF0.width); WriteByte(SOF0.num_comp); WriteByte(SOF0.Y.id); WriteByte(SOF0.Y.sample); WriteByte(SOF0.Y.quant_table_id); WriteByte(SOF0.Cb.id); WriteByte(SOF0.Cb.sample); WriteByte(SOF0.Cb.quant_table_id); WriteByte(SOF0.Cr.id); WriteByte(SOF0.Cr.sample); WriteByte(SOF0.Cr.quant_table_id); JFIF_DHT *dht[4]; dht[0] = &DHT_Luma_dc; dht[1] = &DHT_Chroma_dc; dht[2] = &DHT_Luma_ac; dht[3] = &DHT_Chroma_ac; for (int i=0; i<4; i++) { WriteWord(dht[i]->marker); WriteWord(dht[i]->len); WriteByte(dht[i]->id); for (int j=0; j<16; j++) { WriteByte(dht[i]->bits[j]); } for (int j=0; j<dht[i]->size_var; j++) { WriteByte(dht[i]->var[j]); } } WriteWord(SOS.marker); WriteWord(SOS.len); WriteByte(SOS.num_comp); WriteWord(SOS.luma); WriteWord(SOS.chroma1); WriteWord(SOS.chroma2); WriteByte(SOS.spectral[0]); WriteByte(SOS.spectral[1]); WriteByte(SOS.spectral[2]); for (int i=0; i<data_size; i++) { WriteByte(data[i]); } WriteWord(EOI_marker); fclose(fp); }
// 将采集到的数据保存到文件中 void CTabSample::OnSaveToFile(int iMathValueIdNum, int iGraphViewNum, char** cppSelectObjectName, vector <double>* dSampleData) { CString strFileName = ""; SYSTEMTIME sysTime; GetLocalTime(&sysTime); strFileName.Format("%s\\%04d%02d%02d%02d%02d%02d%04d.text", m_csSaveFilePath,sysTime.wYear,sysTime.wMonth,sysTime.wDay, sysTime.wHour,sysTime.wMinute,sysTime.wSecond,sysTime.wMilliseconds); // 将ADC采样数据及运算结果保存成ANSI格式的文件 errno_t err; FILE * savefile; CString strTemp = ""; unsigned int iDataLength = 0; if((err = fopen_s(&savefile,strFileName,"w+"))==NULL) { CString strOutput = ""; // 输出仪器标签 for (int i=0; i<iGraphViewNum; i++) { strTemp.Format("%s\t\t",cppSelectObjectName[i]); strOutput += strTemp; } strOutput += "\r\n"; // 输出各仪器采样数据 for (unsigned int i=0; i<(m_iMaxLength-iMathValueIdNum); i++) { for (int j=0; j<iGraphViewNum; j++) { if (m_iSelectObject[j] == 1) { if (m_iSelectObjectNoise[j] == 0) { iDataLength = dSampleData[j].size()-iMathValueIdNum; if (iDataLength <= 0 ) { strOutput += "\t\t"; continue; } if (iDataLength > i) { strTemp.Format("%2.9f\t",dSampleData[j][i]); strOutput += strTemp; } else { strOutput += "\t\t"; } } else { strOutput += "\t\t"; } } else { strOutput += "\t\t"; } } strOutput += "\r\n"; } strOutput += "\r\n数据处理结果:\r\n"; // 输出仪器标签 for (int i=0; i<iGraphViewNum; i++) { strTemp.Format("%s\t\t",cppSelectObjectName[i]); strOutput += strTemp; } strOutput += "\r\n"; for (int i=0; i<iMathValueIdNum; i++) { if (i == 0) { strOutput += "平均值:\r\n"; } else if (i == 1) { strOutput += "均方根:\r\n"; } else if (i == 2) { strOutput += "最大值:\r\n"; } else if (i == 3) { strOutput += "最小值:\r\n"; } for (int j=0; j<iGraphViewNum; j++) { if (m_iSelectObject[j] == 1) { if (m_iSelectObjectNoise[j] == 0) { iDataLength = dSampleData[j].size()-iMathValueIdNum; if (iDataLength < 0) { strOutput += "\t\t"; continue; } strTemp.Format("%2.9f\t",dSampleData[j][iDataLength+i]); strOutput += strTemp; } else { strOutput += "\t\t"; } } else { strOutput += "\t\t"; } } strOutput += "\r\n\r\n"; } fprintf(savefile,"%s", strOutput); } fclose(savefile); // 数据采集结束后存ADC采样文件 OnSaveADCDataToFile(iMathValueIdNum, iGraphViewNum, cppSelectObjectName, dSampleData, sysTime); }
WAVERESULT CWaves::ParseFile(const char *szFilename, LPWAVEFILEINFO pWaveInfo) { WAVEFILEHEADER waveFileHeader; RIFFCHUNK riffChunk; WAVEFMT waveFmt; WAVERESULT wr = WR_BADWAVEFILE; if (!szFilename || !pWaveInfo) return WR_INVALIDPARAM; memset(pWaveInfo, 0, sizeof(WAVEFILEINFO)); // Open the wave file for reading fopen_s(&pWaveInfo->pFile, szFilename, "rb"); if (pWaveInfo->pFile) { // Read Wave file header fread(&waveFileHeader, 1, sizeof(WAVEFILEHEADER), pWaveInfo->pFile); if (!_strnicmp(waveFileHeader.szRIFF, "RIFF", 4) && !_strnicmp(waveFileHeader.szWAVE, "WAVE", 4)) { while (fread(&riffChunk, 1, sizeof(RIFFCHUNK), pWaveInfo->pFile) == sizeof(RIFFCHUNK)) { if (!_strnicmp(riffChunk.szChunkName, "fmt ", 4)) { if (riffChunk.ulChunkSize <= sizeof(WAVEFMT)) { fread(&waveFmt, 1, riffChunk.ulChunkSize, pWaveInfo->pFile); // Determine if this is a WAVEFORMATEX or WAVEFORMATEXTENSIBLE wave file if (waveFmt.usFormatTag == WAVE_FORMAT_PCM) { pWaveInfo->wfType = WF_EX; memcpy(&pWaveInfo->wfEXT.Format, &waveFmt, sizeof(PCMWAVEFORMAT)); } else if (waveFmt.usFormatTag == WAVE_FORMAT_EXTENSIBLE) { pWaveInfo->wfType = WF_EXT; memcpy(&pWaveInfo->wfEXT, &waveFmt, sizeof(WAVEFORMATEXTENSIBLE)); } } else { fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR); } } else if (!_strnicmp(riffChunk.szChunkName, "data", 4)) { pWaveInfo->ulDataSize = riffChunk.ulChunkSize; pWaveInfo->ulDataOffset = ftell(pWaveInfo->pFile); fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR); } else { fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR); } // Ensure that we are correctly aligned for next chunk if (riffChunk.ulChunkSize & 1) fseek(pWaveInfo->pFile, 1, SEEK_CUR); } if (pWaveInfo->ulDataSize && pWaveInfo->ulDataOffset && ((pWaveInfo->wfType == WF_EX) || (pWaveInfo->wfType == WF_EXT))) wr = WR_OK; else fclose(pWaveInfo->pFile); } } else { wr = WR_INVALIDFILENAME; } return wr; }