void getNextTokens() { string myLine; while(!myReadFile.eof()){ getline(myReadFile,myLine); if(!myReadFile.fail()) { lNumber++; } char_separator<char> sep(" \n\t\0"); tokenizer<char_separator<char> > toks(myLine,sep); for(tokenizer<char_separator<char> >::iterator it = toks.begin(); it != toks.end(); ++it) { token t; t.value = *it; t.lineNumber = lNumber; t.lineOffset =(it.base() - myLine.begin() - it->size()) + 1; lastLineOffset = strlen(myLine.c_str()) + 1; lastLineNumber = lNumber; tokens.insert(tokens.end(),t); // cout << "token : " << t.value << " lineNumber: " << t.lineNumber << " lineOffset : " << t.lineOffset << endl; } if(!myReadFile.fail()) { lastLineOffset = strlen(myLine.c_str()) + 1; lastLineNumber = lNumber; } } for(list<token>::iterator it = tokens.begin(); it != tokens.end(); ++it) { // cout << "token : " << it->value << " lineNumber: " << it->lineNumber << " lineOffset : " << it->lineOffset << endl; } }
/* SaveMap overwrites the data file with a current version of the map */ void DATABASE::SaveMap(void) { string temp; char* cstr; ofstream file; file.open(IOFILE,ios::trunc); if (file.eof()) cout<<"eofbit set"<<endl; if (file.fail()) cout<<"failbit set"<<endl; if (file.bad()) cout<<"badbit set"<<endl; if (file.fail()) { cout<<"\nFile read\\write failed: SaveMap()\n"; exit(777); } for (iter = mymap.begin(); iter != mymap.end(); ++iter) { temp = iter->second; // converting string to array cstr = new char [temp.size()+1]; strcpy(cstr,temp.c_str()); cstr[temp.size()]='\n'; file.write(cstr,temp.size()+1); delete cstr; } file.close(); cout<<"File saved."<<endl; }
int CRcvBuffer::readBufferToFile(fstream& ofs, int len) { int p = m_iStartPos; int lastack = m_iLastAckPos; int rs = len; while ((p != lastack) && (rs > 0)) { int unitsize = m_pUnit[p]->m_Packet.getLength() - m_iNotch; if (unitsize > rs) unitsize = rs; ofs.write(m_pUnit[p]->m_Packet.m_pcData + m_iNotch, unitsize); if (ofs.fail()) break; if ((rs > unitsize) || (rs == m_pUnit[p]->m_Packet.getLength() - m_iNotch)) { CUnit* tmp = m_pUnit[p]; m_pUnit[p] = NULL; tmp->m_iFlag = 0; --m_pUnitQueue->m_iCount; if (++p == m_iSize) p = 0; m_iNotch = 0; } else m_iNotch += rs; rs -= unitsize; } m_iStartPos = p; return len - rs; }
int main(int argc, char **argv) { std::string path = ros::package::getPath("aida"); file.open((path + "/data").c_str(), ios::in | ios::out | ios::binary); ROS_INFO("%s", (path + "/data").c_str()); if (file.fail()) ROS_FATAL("Cannot open data file for learning algorithm."); ros::init(argc, argv, "la"); ros::NodeHandle n; ros::ServiceServer service = n.advertiseService("get_direction", getDirection); ros::ServiceServer update_sub = n.advertiseService("result", update); ros::Rate loop_rate(LOOP_RATE); while (ros::ok()) { file.flush(); ros::spinOnce(); loop_rate.sleep(); } file.close(); return 0; }
/* * Given a (pre-formatted) string and file stream, appends the string to the log file * Places a timestamp at the start of the string * Places a newline at the end of the string if one is not at the end of the string * Throws log_fail_ex if the log is not open */ void append_raw_to_log(fstream& log, string s) { if (!log.is_open()) { throw log_fail_ex; } time_t current_time; time(¤t_time); log << ctime(¤t_time) << s; if (s[s.size() - 1] != '\n') { log << endl; }else { flush(log); } if (log.fail()) { throw log_fail_ex; } }
bool CCoder::decodeRLE( fstream& in, CFastOStream& out ) { uint32_t blockSize = 0; uint32_t lastBlockSize = 0; uint32_t blockCount = 0; in.seekg( -12, in.end ); logger.setFileSize( (size_t) in.tellg() + 12 ); in.read( (char *) &blockSize, 4 ); in.read( (char *) &lastBlockSize, 4 ); in.read( (char *) &blockCount, 4 ); in.seekg( -12 - (int64_t)blockCount * 4, in.end ); vector<uint32_t> header; header.resize( blockCount, 0 ); in.read( (char *) &header.front(), blockCount * 4 ); if ( in.fail() ) return false; logger.updateInput( blockCount * 4 + 12 ); in.clear(); in.seekg( 0, in.beg ); CFISFromStream inStream( in ); return decodeRLE( inStream, out, header, blockSize, lastBlockSize, blockCount ); }
int main(){ ifs.open("/usr/share/dict/words",ios::in); if(ifs.fail()){ std::cerr << "失敗" << std::endl; return -1; } std::cout << "Pleas input 16 words!" << endl; cin >> table; transform(table.begin(), table.end(), table.begin(), ::tolower); sort(table.begin(), table.end()); search(); std::cout << "answer is :" << answer << std::endl; ifs.close(); return 0; }
/* * Given a string containing an action that occurred and the result of that action, appends the string and the result to the log file * Places a timestamp at the start of the string * Places a newline at the end of the string * Throws log_fail_ex if the log is not open */ void append_action_to_log(fstream& log, string s, bool result) { if (!log.is_open()) { throw log_fail_ex; } time_t current_time; time(¤t_time); //FIXME remove newline char at the end of ctime log << ctime(¤t_time) << ": " << s; if (result) { log << " (SUCCESS)"; }else { log << " (FAILURE)"; } log << endl; if (log.fail()) { throw log_fail_ex; } }
// read and return descriptor area (headers + entries) Int32 readDescArea (fstream &mf, // (IN) : binary module file module_header_struct &latestModHdr,// (IN) : its module header NAHeap &heap, // (IN) : allocate DESC area from here const char * name, // (IN) : module name (for error msg) ComDiagsArea &diags, // (IN) : deposit any error msg here char *&descArea) // (OUT): desc headers + entries { // make sure we have reasonable arguments if (latestModHdr.descriptor_area_offset <= 0 || latestModHdr.descriptor_area_length <= 0) return -1; // allocate space for DESC headers + entries descArea = (char*) heap.allocateMemory((size_t)latestModHdr.descriptor_area_length); // read DESC headers + entries mf.seekg(latestModHdr.descriptor_area_offset, ios::beg); mf.read(descArea, (Int32)latestModHdr.descriptor_area_length); if (mf.fail()) { diags << DgSqlCode(-CLI_READ_ERROR) << DgString0(name); return -1; } return 1; // all OK }
/* Given: InputFile A file stream already opened for input. Task: To read the data from InputFile and load it into the Table. Return: Table The B-tree table containing the data. */ void Load(fstream & InputFile, BTTableClass & Table) { ItemType Item; int Count; Count = 0; ReadLine(InputFile, Item.KeyField, Item.DataField); while (! InputFile.fail()) { #ifdef DEBUG Count++; if (Count == 22) { Count = 0; cout << endl << "Press ENTER"; cin.get(); } cout << endl << "DEBUG: ready to insert " << Item.KeyField << " "; #endif Table.Insert(Item); #ifdef DEBUG Table.Check(); #endif ReadLine(InputFile, Item.KeyField, Item.DataField); } }
bool openfile(fstream &file, string name) { file.open(name.c_str(), ios::in); if (file.fail()) return false; else return true; }
bool openFileIn(fstream &file, char *name) { file.open(name, ios::in); if (file.fail()) return false; else return true; }
void showState(fstream &file) { cout << "File Status:\n"; cout << " eof bit: " << file.eof() << endl; cout << " fail bit: " << file.fail() << endl; cout << " bad bit: " << file.bad() << endl; cout << " good bit: " << file.good() << endl; file.clear(); // Clear any bad bits }
void write(Record r) { if (in_cache(r.user_id)) write_to_cache(r); file.seekp(r.user_id * sizeof(Record)); file.write((char*)&r, sizeof(Record)); if (file.fail()) ROS_ERROR("Failed to write record to file. user_id=%d", r.user_id); }
bool find(fstream& file,unsigned int& loc, Employee& F){ Employee E; bool found = false; while(!file.fail()){ file.read((char*)&E, sizeof(Employee)); if(E == F){ loc = (unsigned int)file.tellg() - sizeof(E); found = true; } } return found; }
void openFileOutput(string& filePath) { bool fileError = true; do{ file.open(filePath); if(file.fail()) {filePath = getFileName();} else {fileError = false;} }while(fileError); }
int CSndBuffer::addBufferFromFile(fstream& ifs, int len) { int size = len / m_iMSS; if ((len % m_iMSS) != 0) size ++; // dynamically increase sender buffer while (size + m_iCount >= m_iSize) increase(); Block* s = m_pLastBlock; int total = 0; for (int i = 0; i < size; ++ i) { if (ifs.bad() || ifs.fail() || ifs.eof()) break; size_t pktlen = len - i * m_iMSS; if (pktlen > m_iMSS) pktlen = m_iMSS; ifs.read(s->m_pcData, pktlen); pktlen = ifs.gcount(); if (pktlen <= 0) break; // currently file transfer is only available in streaming mode, message is always in order, ttl = infinite s->m_iMsgNo = m_iNextMsgNo | 0x20000000; if (i == 0) s->m_iMsgNo |= 0x80000000; if (i == size - 1) s->m_iMsgNo |= 0x40000000; s->m_iLength = pktlen; s->m_iTTL = -1; s = s->m_pNext; total += pktlen; } m_pLastBlock = s; CGuard::enterCS(m_BufLock); m_iCount += size; CGuard::leaveCS(m_BufLock); m_iNextMsgNo ++; if (m_iNextMsgNo == CMsgNo::m_iMaxMsgNo) m_iNextMsgNo = 1; return total; }
Record read(int user_id) { Record r; if (in_cache(user_id)) return get_from_cache(user_id); file.seekg(user_id * sizeof(Record)); file.read((char*)&r, sizeof(Record)); if (file.fail()) ROS_ERROR("Failed to read record. user_id=%d", r.user_id); else cache.push_back(r); return r; }
/* Given: InFile Text file stream already opened for input. MoreData Indicates if there is more data from InFile to place into Buffer. At the very least this indicates if there is an unused item in NextWord. NextWord If MoreData is true, then NextWord contains an unprocessed word from InFile that has yet to be placed into Buffer. Task: If MoreData is true, this function places as much data as possible from InFile into Buffer. This data includes NextWord and then as much new data as possible from InFile. The Buffer will be filled if there is enough data to do so. Return: In the function name is returned the number of words placed into Buffer. InFile The modified file stream. Buffer Contains the data that has been copied in from InFile. MoreData Indicates if NextWord contains a word that has not yet been placed into Buffer. NextWord If MoreData is true, this contains the next word from InFile that has not yet been placed into Buffer. */ int FillBuffer(fstream & InFile, BufType Buffer, bool & MoreData, StringType NextWord) { int k = 0; while (MoreData && (k < BufSize)) { strcpy(Buffer[k], NextWord); InFile.getline(NextWord, MaxString); if (InFile.fail()) MoreData = false; else MoreData = true; k++; } return k; }
int check_flags(const fstream& fh) { int status = 0; //cout << "file is:\n"; if (fh.good()) status+=16; if (fh.bad()) status+=2; if (fh.fail()) status+=4; if (fh.eof()) status+=8; if (0 == status) status = -1; return status; }
void ReadAlignChunk::chunkFstreamOpen(string filePrefix, int iChunk, fstream &fstreamOut) {//open fstreams for chunks ostringstream fNameStream1; fNameStream1 << filePrefix << iChunk; string fName1=fNameStream1.str(); P->inOut->logMain << "Opening the file: " << fName1 << " ... " <<flush; remove(fName1.c_str()); //remove the file fstreamOut.open(fName1.c_str(),ios::out); //create empty file fstreamOut.close(); fstreamOut.open(fName1.c_str(), ios::in | ios::out); //re-open the file in in/out mode if (fstreamOut.fail()) { P->inOut->logMain << "failed!\n"; ostringstream errOut; errOut << "EXITING because of FATAL ERROR: could not create output file "<< fName1 << "\n"; errOut << "Solution: check that you have permission to write this file\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; P->inOut->logMain << "ok" <<endl; };
/* Given: DataFile A text file stream already opened for input. FileName The name of this text file (as a char array string). Task: To copy data from this file stream into sorted files (runs). Return: DataFile The modified file stream is trivially modified by reading from it. In the function name the number of runs is returned. The sorted runs themselves are created and stored under the file names: ExtSortTemp.0, ExtSortTemp.1, etc. */ int MakeSortedRuns(fstream & DataFile, PathType FileName) { fstream OutFile; StringType Word, Extension; PathType OutFileName; int NumWords, k, NumFiles = 0; BufType Buffer; bool MoreData; // Repeatedly fill one buffer and quicksort it, writing the buffer out to a temp file. DataFile.getline(Word, MaxString); if (DataFile.fail()) MoreData = false; else MoreData = true; while (MoreData) { // Fill one buffer. NumWords = FillBuffer(DataFile, Buffer, MoreData, Word); QuickSort(Buffer, 0, NumWords - 1); // Construct the temp file name. strcpy(OutFileName, "ExtSortTemp."); _itoa(NumFiles, Extension, 10); // Convert the int in NumFiles to a char array string. strcat(OutFileName, Extension); OutFile.open(OutFileName, ios::out); if (OutFile.fail()) Error("Could not open the file named ", OutFileName); for (k = 0; k < NumWords; k++) OutFile << Buffer[k] << endl; OutFile.close(); NumFiles++; } return NumFiles; }
//这个函数存在问题,不能够处理大于2G的文件。 int CSndBuffer::addBufferFromFile(fstream& ifs, const int& len) { int size = len / m_iMSS; if ((len % m_iMSS) != 0) size ++; // dynamically increase sender buffer while (size + m_iCount >= m_iSize) increase(); Block* s = m_pLastBlock; int total = 0; for (int i = 0; i < size; ++ i) { if (ifs.bad() || ifs.fail() || ifs.eof()) break; int pktlen = len - i * m_iMSS; if (pktlen > m_iMSS) pktlen = m_iMSS; ifs.read(s->m_pcData, pktlen); if ((pktlen = ifs.gcount()) <= 0) break; s->m_iLength = pktlen; s->m_iTTL = -1; s = s->m_pNext; total += pktlen; } m_pLastBlock = s; CGuard::enterCS(m_BufLock); m_iCount += size; CGuard::leaveCS(m_BufLock); return total; }
// read and return a binary module file's source area SourceBuf readSourceArea (fstream &mf, // (IN) : binary module file module_header_struct &latestModHdr,// (IN) : its module header NAHeap &heap, // (IN) : allocate PLT area from here const char * name, // (IN) : module name (for error msg) ComDiagsArea &diags) // (IN) : deposit any error msg here { SourceBuf srcArea = NULL; if (latestModHdr.source_area_length > 0) { // allocate space for source area srcArea = (SourceBuf) heap.allocateMemory((size_t)latestModHdr.source_area_length); // read source area mf.seekg(latestModHdr.source_area_offset, ios::beg); mf.read(srcArea, (Int32)latestModHdr.source_area_length); if (mf.fail()) { diags << DgSqlCode(-CLI_READ_ERROR) << DgString0(name); return NULL; } } return srcArea; }
int init(int argc, char *argv[]) { // open input, output files if (argc!=5) { cerr << "Incorrect number of arguments." << endl; cerr << "Usage: orca.exe [orbit type: node|edge] [graphlet size: 4/5] [graph - input file] [graphlets - output file]" << endl; return 0; } orbit_type = argv[1]; if (orbit_type!="node" && orbit_type!="edge") { cerr << "Incorrect orbit type '" << argv[1] << "'. Should be 'node' or 'edge'." << endl; return 0; } sscanf(argv[2],"%d",&GS); if (GS!=4 && GS!=5) { cerr << "Incorrect graphlet size " << argv[2] << ". Should be 4 or 5." << endl; return 0; } fin.open(argv[3], fstream::in); fout.open(argv[4], fstream::out | fstream::binary); if (fin.fail()) { cerr << "Failed to open file " << argv[2] << endl; return 0; } if (fout.fail()) { cerr << "Failed to open file " << argv[3] << endl; return 0; } // read input graph fin >> n >> m; int d_max=0; edges = (PAIR*)malloc(m*sizeof(PAIR)); deg = (int*)calloc(n,sizeof(int)); for (int i=0;i<m;i++) { int a,b; fin >> a >> b; if (!(0<=a && a<n) || !(0<=b && b<n)) { cerr << "Node ids should be between 0 and n-1." << endl; return 0; } if (a==b) { cerr << "Self loops (edge from x to x) are not allowed." << endl; return 0; } deg[a]++; deg[b]++; edges[i]=PAIR(a,b); } for (int i=0;i<n;i++) d_max=max(d_max,deg[i]); printf("nodes: %d\n",n); printf("edges: %d\n",m); printf("max degree: %d\n",d_max); fin.close(); if ((int)(set<PAIR>(edges,edges+m).size())!=m) { cerr << "Input file contains duplicate undirected edges." << endl; return 0; } // set up adjacency matrix if it's smaller than 100MB if ((int64)n*n < 100LL*1024*1024*8) { adjacent = adjacent_matrix; adj_matrix = (int*)calloc((n*n)/adj_chunk+1,sizeof(int)); for (int i=0;i<m;i++) { int a=edges[i].a, b=edges[i].b; adj_matrix[(a*n+b)/adj_chunk]|=(1<<((a*n+b)%adj_chunk)); adj_matrix[(b*n+a)/adj_chunk]|=(1<<((b*n+a)%adj_chunk)); } } else { adjacent = adjacent_list; } // set up adjacency, incidence lists adj = (int**)malloc(n*sizeof(int*)); for (int i=0;i<n;i++) adj[i] = (int*)malloc(deg[i]*sizeof(int)); inc = (PII**)malloc(n*sizeof(PII*)); for (int i=0;i<n;i++) inc[i] = (PII*)malloc(deg[i]*sizeof(PII)); int *d = (int*)calloc(n,sizeof(int)); for (int i=0;i<m;i++) { int a=edges[i].a, b=edges[i].b; adj[a][d[a]]=b; adj[b][d[b]]=a; inc[a][d[a]]=PII(b,i); inc[b][d[b]]=PII(a,i); d[a]++; d[b]++; } for (int i=0;i<n;i++) { sort(adj[i],adj[i]+deg[i]); sort(inc[i],inc[i]+deg[i]); } // initialize orbit counts orbit = (int64**)malloc(n*sizeof(int64*)); for (int i=0;i<n;i++) orbit[i] = (int64*)calloc(73,sizeof(int64)); // initialize edge orbit counts eorbit = (int64**)malloc(m*sizeof(int64*)); for (int i=0;i<m;i++) eorbit[i] = (int64*)calloc(68,sizeof(int64)); return 1; }
int init(int maxGraphletSize, const char* graphFileName) { // open input, output files GS = maxGraphletSize; if (GS!=4 && GS!=5) { cerr << "Incorrect graphlet size " << maxGraphletSize << ". Should be 4 or 5." << endl; return 0; } fin.open(graphFileName, fstream::in); // fout.open(argv[3], fstream::out | fstream::binary); if (fin.fail()) { cerr << "Failed to open file " << graphFileName << endl; return 0; } // if (fout.fail()) { // cerr << "Failed to open file " << argv[3] << endl; // return 0; // } // read input graph fin >> n >> m; int d_max=0; edges = (PAIR*)malloc(m*sizeof(PAIR)); deg = (int*)calloc(n,sizeof(int)); for (int i=0;i<m;i++) { int a,b; fin >> a >> b; if (!(0<=a && a<n) || !(0<=b && b<n)) { cerr << "Node ids should be between 0 and n-1." << endl; return 0; } if (a==b) { cerr << "Self loops (edge from x to x) are not allowed." << endl; return 0; } deg[a]++; deg[b]++; edges[i]=PAIR(a,b); } for (int i=0;i<n;i++) d_max=max(d_max,deg[i]); fprintf(stderr,"nodes: %d\n",n); fprintf(stderr,"edges: %d\n",m); fprintf(stderr,"max degree: %d\n",d_max); fin.close(); if ((int)(set<PAIR>(edges,edges+m).size())!=m) { cerr << "Input file contains duplicate undirected edges." << endl; return 0; } // set up adjacency matrix if it's smaller than 100MB if ((int64)n*n < 100LL*1024*1024*8) { adjacent = adjacent_matrix; adj_matrix = (int*)calloc((n*n)/adj_chunk+1,sizeof(int)); for (int i=0;i<m;i++) { int a=edges[i].a, b=edges[i].b; adj_matrix[(a*n+b)/adj_chunk]|=(1<<((a*n+b)%adj_chunk)); adj_matrix[(b*n+a)/adj_chunk]|=(1<<((b*n+a)%adj_chunk)); } } else { adjacent = adjacent_list; } // set up adjacency, incidence lists adj = (int**)malloc(n*sizeof(int*)); for (int i=0;i<n;i++) adj[i] = (int*)malloc(deg[i]*sizeof(int)); inc = (PII**)malloc(n*sizeof(PII*)); for (int i=0;i<n;i++) inc[i] = (PII*)malloc(deg[i]*sizeof(PII)); int *d = (int*)calloc(n,sizeof(int)); for (int i=0;i<m;i++) { int a=edges[i].a, b=edges[i].b; adj[a][d[a]]=b; adj[b][d[b]]=a; inc[a][d[a]]=PII(b,i); inc[b][d[b]]=PII(a,i); d[a]++; d[b]++; } for (int i=0;i<n;i++) { sort(adj[i],adj[i]+deg[i]); sort(inc[i],inc[i]+deg[i]); } // initialize orbit counts orbit = (int64**)malloc(n*sizeof(int64*)); for (int i=0;i<n;i++) orbit[i] = (int64*)calloc(73,sizeof(int64)); return 1; }
// read and return procedure location table area (header + entries) Int32 readPLTArea (fstream &mf, // (IN) : binary module file module_header_struct &latestModHdr,// (IN) : its module header NAHeap &heap, // (IN) : allocate PLT area from here const char * name, // (IN) : module name (for error msg) ComDiagsArea &diags, // (IN) : deposit any error msg here plt_header_struct *&pltArea) // (OUT): plt header + entries { // make sure we have reasonable arguments if (latestModHdr.plt_area_offset <= 0 || latestModHdr.plt_area_length <= 0 || latestModHdr.plt_hdr_length <= 0 || latestModHdr.plt_entry_length <= 0) return -1; // allocate space for PLT header plt_header_struct pltHdrCls, *latestPLTHdr, *plt; plt = (plt_header_struct *) heap.allocateMemory(latestModHdr.plt_hdr_length); // read procedure location table header mf.seekg(latestModHdr.plt_area_offset, ios::beg); mf.read((char *)plt, latestModHdr.plt_hdr_length); if (mf.fail()) { diags << DgSqlCode(-CLI_READ_ERROR) << DgString0(name); return -1; } // give versioning a chance to massage/migrate it to this version latestPLTHdr = (plt_header_struct*)plt->driveUnpack(plt, &pltHdrCls,NULL); if (!latestPLTHdr) { // error: version is no longer supported diags << DgSqlCode(-CLI_MOD_PLT_HDR_VERSION_ERROR) << DgString0(name); return -1; } pltArea = latestPLTHdr; Int32 num_procs = latestPLTHdr->num_procedures; if (num_procs >= 1) { // allocate space for PLT header + entries heap.deallocateMemory(plt); plt = (plt_header_struct *) heap.allocateMemory((size_t)latestModHdr.plt_area_length); // read procedure location table header + entries mf.seekg(latestModHdr.plt_area_offset, ios::beg); mf.read((char *)plt, (Int32)latestModHdr.plt_area_length); if (mf.fail()) { diags << DgSqlCode(-CLI_READ_ERROR) << DgString0(name); return -1; } // give versioning a chance to massage/migrate it to this version latestPLTHdr = (plt_header_struct*)plt->driveUnpack(plt, &pltHdrCls, NULL); if (!latestPLTHdr) { // error: version is no longer supported diags << DgSqlCode(-CLI_MOD_PLT_HDR_VERSION_ERROR) << DgString0(name); return -1; } pltArea = latestPLTHdr; } // verify its validity Lng32 errCode = pltArea->RtduStructIsCorrupt(); if (errCode) { // the module file is corrupted or has invalid data diags << DgSqlCode(errCode) << DgString0(name); heap.deallocateMemory(plt); return -1; } return num_procs; }
int main(int argc, char **argv) { int status = 0; WSADATA wsaData; int iResult; HANDLE hReadClient; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); status = -1; } else { struct addrinfo *result = NULL; struct addrinfo *ptr = NULL; struct addrinfo hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the local address and port to be used by the server iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed: %d\n", iResult); WSACleanup(); status = -1; } else { // Create a SOCKET for the server to listen for client connections ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { printf("Error at socket(): %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); status = -1; } else { // Setup the TCP listening socket iResult = ::bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); freeaddrinfo(result); if (iResult == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); status = -1; } else { printf("Server started\n\n"); printf("Listenning...\n"); if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) { printf("Listen failed with error: %ld\n", WSAGetLastError()); } else { // trying to create/open a file to store users records stream.open("DataBase.txt", ios::in | ios::out | ios::trunc); if (stream.fail()) { printf("Can not open the database, trying to create a file...\n"); stream.open("DataBase.txt", ios::out); stream.close(); stream.open("DataBase.txt", ios::in | ios::out); if (stream.fail()) { printf("Failed to create a file\n"); } else { printf("Created a file\n"); } } stream.close(); // creating a mutex for the ID idMutex = CreateMutex(NULL, FALSE, NULL); if (idMutex == NULL) { printf("Can not create mutex :%d\n", GetLastError()); closesocket(ListenSocket); WSACleanup(); vec.clear(); return 0; } // creating a mutex for the stream streamMutex = CreateMutex(NULL, FALSE, NULL); if (streamMutex == NULL) { printf("Can not create mutex :%d\n", GetLastError()); closesocket(ListenSocket); WSACleanup(); vec.clear(); return 0; } // creating a mutex for the vector with users vecMutex = CreateMutex(NULL, FALSE, NULL); if (streamMutex == NULL) { printf("Can not create mutex :%d\n", GetLastError()); closesocket(ListenSocket); WSACleanup(); vec.clear(); return 0; } // starting the thread to read input from the server operator CreateThread(NULL, 0, readServer, 0, 0, NULL); // loop to accept clients and creating threads for them while (1) { SOCKET ClientSocket = INVALID_SOCKET; // Accept a client socket ClientSocket = accept(ListenSocket, NULL, NULL); if (ClientSocket == INVALID_SOCKET) { printf("accept failed: %d\n", WSAGetLastError()); } else { // creating a thread for a client and adding it to the list hReadClient = CreateThread(NULL, 0, readClient, (LPVOID)ClientSocket, 0, NULL); WaitForSingleObject(vecMutex, INFINITE); vec.push_back(ClientSocket); ReleaseMutex(vecMutex); printf("Added a client with %d\n", ClientSocket); } } } // cleanup int i = 0; for (vector<SOCKET>::iterator iter = vec.begin(); iter < vec.end(); iter++, i++) { closesocket(vec[i]); } WSACleanup(); vec.clear(); CloseHandle(idMutex); CloseHandle(streamMutex); CloseHandle(vecMutex); } } } } return status; }