Search Results

Search found 113 results on 5 pages for 'ofstream'.

Page 3/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Getting meaningful error messages from fstream's in C++

    - by Hassan Syed
    What is the best way to get meaningful file access error messages, in a portable way from std::fstreams ? The primitiveness of badbits and failbits is getting to be bit annoying. I have written my own exception hierarchies against win32 and POSIX before, and that was far more flexible than the way the STL does it. I am getting "basic::ios_clear" as an error message from the what method of a downcasted catch (std::exception) of a fstream which has exceptions enabled. This doesn't mean much to me, although I do know what the problem is I'd like my program to be a tad more informative so that when I start deployment a few months later my life will be easier. Is there anything in Boost to extract meaningful messages out of the ofstream's implementation cross platform and cross STL implementation ?

    Read the article

  • vector segmentation fault

    - by user1849298
    I have a problem with the segmentation fault. Look: #include<fstream> using namespace std; int main(){ int n,i,vector[10001],vectorcopy[10001]; ifstream in("program.in"); ofstream out("program.out"); in>>n; for(i=1;i<=n;i++){ in>>vector[i]; vectorcopy[i]=vector[i]; } return 0;} And the debugger says: Program recived signal SIGSEGV, Segmentation fault Please, tell me what to do!

    Read the article

  • C++ - Where to code a member function for an inherited object.

    - by Francisco P.
    Hello! I have a few classes (heat, gas, contact, pressure) inheriting from a main one (sensor). I have a need to store them in a vector<Sensor *> (part of the specification). At some point in time, I need to call a function that indiscriminately stores those Sensor *. (also part of the specification, not open for discussion) Something like this: for(size_t i = 0; i < Sensors.size(); ++i) Sensors[i]->storeSensor(os) //os is an ofstream kind of object, passed onwards by reference Where and how shall storeSensor be defined? Is there any simple way to do this or will I need to disregard the specification? Mind you, I'm a beginner! Thanks for your time!

    Read the article

  • Write data into .txt file created by CFileDialog, in C++

    - by younevertell
    I wanna Write data into .txt file created by CFileDialog, in C++. The problem I am facing is that below codes doesn't work, although there is no build error. The .txt file created by CFileDialog can not be found for some reason. What's wrong the code? what's the efficient way to Write data into .txt file created by CFileDialog, in C++? Thanks CFileDialog dlg(FALSE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("My Data File (*.txt)|*.txt||")); if(dlg.DoModal() != IDOK) return; CString filename = dlg.GetPathName(); ofstream outfile (filename); int mydata = 10; outfile << "my data:" << mydata << endl; outfile.close();

    Read the article

  • simple c++ file opening issue

    - by Robert
    #include <iostream> #include <fstream> using namespace std; int main () { ofstream testfile; testfile.open ("test.txt"); testfile << "success!\n"; testfile.close(); return 0; } 1)called "g++ testfile.cpp" 2)created "test.txt" 3)called "chmod u+x a.out" 4)??? 5)file remains blank. I feel like an idiot for failing at something as trivial as this is supposed to be.

    Read the article

  • C++ - How to call a member function for an inherited object.

    - by Francisco P.
    Hello! I have a few classes (heat, gas, contact, pressure) inheriting from a main one (sensor). I have a need to store them in a vector<Sensor *> (part of the specification). At some point in time, I need to call a function that indiscriminately stores those Sensor *. (also part of the specification, not open for discussion) Something like this: for(size_t i = 0; i < Sensors.size(); ++i) Sensors[i]->storeSensor(os) //os is an ofstream kind of object, passed onwards by reference Where and how shall storeSensor be defined? Is there any simple way to do this or will I need to disregard the specification? Mind you, I'm a beginner! Thanks for your time!

    Read the article

  • Can nohup change the result of a C++ code?

    - by Biga
    I am having this very weird behaviour with a C++ code: It gives me different results when running with and without 'nohup' (reproducible in cygwin and linux). I mean, if I get the same executable and run it like './run' or run it like 'nohup ./run out.log', I get different results! I use std::cout to output to screen, all lines ending with endl; I use ifstream for the input file; I use ofstream for output, all lines ending with endl. I am using g++ 4. Any idea what is going on?

    Read the article

  • how divide herader from binary data

    - by fixo2020
    Hi, I have this code: ofstream dest("test.txt",ios::binary); while (true){ size_t retval = recv (sd, buffer, sizeof(buffer), 0); dest.write(buffer,retval); if(retval <= 0) { delete[] buffer; break;} } Now, the recv() function return 4 bytes each loop right? and buffer contain it, this return all data so, pseudo-header and binary data (image), but I want know how capture only binary data, I know that the end of header are "\n\r" right? but what's are the solution better for make this? I make a function that detect when are "\n\r"? and after how capture binary data? Or, I put all data in memory, and after parse it? but how? I'm desperate :(

    Read the article

  • C++ how to store integer into a binary file??

    - by blaxc
    i gt a struct with 2 integer, i want to store them in a binary file and read it again... here is my code... struct pw { int a; int b; }; void main(){ pw* p = new pw(); pw* q = new pw(); std::ofstream fout(ADMIN_FILE, ios_base::out | ios_base::binary | ios_base::trunc); std::ifstream fin(ADMIN_FILE, ios_base::in | ios_base::binary); p->a=123; p->b=321; fout.write((const char*)p, sizeof(pw)); fin.write((char*)q, sizeof(pw)); fin.close(); cout<< q->a << endl;} my output is 0. anyone can tell me what is the problem?

    Read the article

  • Can anyone explain why my crypto++ decrypted file 16 bytes short?

    - by Tom Williams
    I suspect it might be too much to hope for, but can anyone with experience with crypto++ explain why the "decrypted.out" file created by main() is 16 characters short (which probably not coincidentally is the block size)? I think the issue must be in CryptStreamBuffer::GetNextChar(), but I've been staring at it and the crypto++ documentation for hours. Any other comments about how crummy or naive my std::streambuf implementation are also welcome ;-) And I've just noticed I'm missing some calls to delete so you don't have to tell me about those. Thanks, Tom // Runtime Includes #include <iostream> // Crypto++ Includes #include "aes.h" #include "modes.h" // xxx_Mode< > #include "filters.h" // StringSource and // StreamTransformation #include "files.h" using namespace std; class CryptStreamBuffer: public std::streambuf { public: CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c); CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c); protected: virtual int_type overflow(int_type ch = traits_type::eof()); virtual int_type uflow(); virtual int_type underflow(); virtual int_type pbackfail(int_type ch); virtual int sync(); private: int GetNextChar(); int m_NextChar; // Buffered character CryptoPP::StreamTransformationFilter* m_StreamTransformationFilter; CryptoPP::FileSource* m_Source; CryptoPP::FileSink* m_Sink; }; // class CryptStreamBuffer CryptStreamBuffer::CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c); m_Source = new CryptoPP::FileSource(encryptedInput, false, m_StreamTransformationFilter); } CryptStreamBuffer::CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_Sink = new CryptoPP::FileSink(encryptedOutput); m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, m_Sink); } CryptStreamBuffer::int_type CryptStreamBuffer::overflow(int_type ch) { return m_StreamTransformationFilter->Put((byte)ch); } CryptStreamBuffer::int_type CryptStreamBuffer::uflow() { int_type result = GetNextChar(); // Reset the buffered character m_NextChar = traits_type::eof(); return result; } CryptStreamBuffer::int_type CryptStreamBuffer::underflow() { return GetNextChar(); } CryptStreamBuffer::int_type CryptStreamBuffer::pbackfail(int_type ch) { return traits_type::eof(); } int CryptStreamBuffer::sync() { if (m_Sink) { m_StreamTransformationFilter->MessageEnd(); } } int CryptStreamBuffer::GetNextChar() { // If we have a buffered character do nothing if (m_NextChar != traits_type::eof()) { return m_NextChar; } // If there are no more bytes currently available then pump the source // *** I SUSPECT THE PROBLEM IS HERE *** if (m_StreamTransformationFilter->MaxRetrievable() == 0) { m_Source->Pump(1024); } // Retrieve the next byte byte nextByte; size_t noBytes = m_StreamTransformationFilter->Get(nextByte); if (0 == noBytes) { return traits_type::eof(); } // Buffer up the next character m_NextChar = nextByte; return m_NextChar; } void InitKey(byte key[]) { key[0] = -62; key[1] = 102; key[2] = 78; key[3] = 75; key[4] = -96; key[5] = 125; key[6] = 66; key[7] = 125; key[8] = -95; key[9] = -66; key[10] = 114; key[11] = 22; key[12] = 48; key[13] = 111; key[14] = -51; key[15] = 112; } void DecryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ifs, decryptor); std::istream decrypt(&cryptBuf); int c; while (EOF != (c = decrypt.get())) { ofs << (char)c; } ofs.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } void EncryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ofs, encryptor); std::ostream encrypt(&cryptBuf); int c; while (EOF != (c = ifs.get())) { encrypt << (char)c; } encrypt.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } int main(int argc, char* argv[]) { EncryptFile(argv[1], "encrypted.out"); DecryptFile("encrypted.out", "decrypted.out"); return 0; }

    Read the article

  • Can anyone explain why my crypto++ decrypted file is 16 bytes short?

    - by Tom Williams
    I suspect it might be too much to hope for, but can anyone with experience with crypto++ explain why the "decrypted.out" file created by main() is 16 characters short (which probably not coincidentally is the block size)? I think the issue must be in CryptStreamBuffer::GetNextChar(), but I've been staring at it and the crypto++ documentation for hours. Any other comments about how crummy or naive my std::streambuf implementation are also welcome ;-) And I've just noticed I'm missing some calls to delete so you don't have to tell me about those. Thanks, Tom // Runtime Includes #include <iostream> // Crypto++ Includes #include "aes.h" #include "modes.h" // xxx_Mode< > #include "filters.h" // StringSource and // StreamTransformation #include "files.h" using namespace std; class CryptStreamBuffer: public std::streambuf { public: CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c); CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c); protected: virtual int_type overflow(int_type ch = traits_type::eof()); virtual int_type uflow(); virtual int_type underflow(); virtual int_type pbackfail(int_type ch); virtual int sync(); private: int GetNextChar(); int m_NextChar; // Buffered character CryptoPP::StreamTransformationFilter* m_StreamTransformationFilter; CryptoPP::FileSource* m_Source; CryptoPP::FileSink* m_Sink; }; // class CryptStreamBuffer CryptStreamBuffer::CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c); m_Source = new CryptoPP::FileSource(encryptedInput, false, m_StreamTransformationFilter); } CryptStreamBuffer::CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_Sink = new CryptoPP::FileSink(encryptedOutput); m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, m_Sink); } CryptStreamBuffer::int_type CryptStreamBuffer::overflow(int_type ch) { return m_StreamTransformationFilter->Put((byte)ch); } CryptStreamBuffer::int_type CryptStreamBuffer::uflow() { int_type result = GetNextChar(); // Reset the buffered character m_NextChar = traits_type::eof(); return result; } CryptStreamBuffer::int_type CryptStreamBuffer::underflow() { return GetNextChar(); } CryptStreamBuffer::int_type CryptStreamBuffer::pbackfail(int_type ch) { return traits_type::eof(); } int CryptStreamBuffer::sync() { if (m_Sink) { m_StreamTransformationFilter->MessageEnd(); } } int CryptStreamBuffer::GetNextChar() { // If we have a buffered character do nothing if (m_NextChar != traits_type::eof()) { return m_NextChar; } // If there are no more bytes currently available then pump the source // *** I SUSPECT THE PROBLEM IS HERE *** if (m_StreamTransformationFilter->MaxRetrievable() == 0) { m_Source->Pump(1024); } // Retrieve the next byte byte nextByte; size_t noBytes = m_StreamTransformationFilter->Get(nextByte); if (0 == noBytes) { return traits_type::eof(); } // Buffer up the next character m_NextChar = nextByte; return m_NextChar; } void InitKey(byte key[]) { key[0] = -62; key[1] = 102; key[2] = 78; key[3] = 75; key[4] = -96; key[5] = 125; key[6] = 66; key[7] = 125; key[8] = -95; key[9] = -66; key[10] = 114; key[11] = 22; key[12] = 48; key[13] = 111; key[14] = -51; key[15] = 112; } void DecryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ifs, decryptor); std::istream decrypt(&cryptBuf); int c; while (EOF != (c = decrypt.get())) { ofs << (char)c; } ofs.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } void EncryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ofs, encryptor); std::ostream encrypt(&cryptBuf); int c; while (EOF != (c = ifs.get())) { encrypt << (char)c; } encrypt.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } int main(int argc, char* argv[]) { EncryptFile(argv[1], "encrypted.out"); DecryptFile("encrypted.out", "decrypted.out"); return 0; }

    Read the article

  • Strange problem with Random Access Filing in C++

    - by sam
    This is a simple random access filing program . The problem arises where i want to write data randomly. If I write any where in the file the previous records are set to 0. the last 1 which is being entered currently holds the correct value all others =0. This is the code #include <iostream> #include<fstream> #include<string> using namespace std; class name { int id; int pass; public: void writeBlank(); void writedata(); void readdata(); void readall(); int getid() { return id; } int getpass() { return pass; } void setid(int i) { id=i; } void setpass(int p) { pass=p; } }; void name::writeBlank() { name person; person.setid(0); person.setpass(0); int i; ofstream out("pass.txt",ios::binary); if ( !out ) { cout << "File could not be opened." << endl; } for(i=0;i<10;i++) //make 10 records { cout<<"Put pointer is at: "<<out.tellp()<<endl; cout<<"Blank record "<<i<<" is: "<<person.getid()<<" "<<person.getpass()<<" and size: "<<sizeof(person)<<endl; cout<<"Put pointer is at: "<<out.tellp()<<endl; out.write(reinterpret_cast< const char * >(&person),sizeof(name)); } } void name::writedata() { ofstream out("pass.txt",ios::binary|ios::out); name n1; int iD,p; cout<<"ID?"; cin>>iD; n1.setid(iD); cout<<"Enter password"; cin>>p; n1.setpass(p); if (!out ) { cout << "File could not be opened." << endl; } out.seekp((n1.getid()-1)*sizeof(name),ios::beg); //pointer moves to desired location where we have to store password according to its ID(index) cout<<"File pointer is at: "<<out.tellp()<<endl; out.write(reinterpret_cast<const char*> (&n1), sizeof(name)); //write on that pointed location } void name::readall() { name n1; ifstream in("pass.txt",ios::binary); if ( !in ) { cout << "File could not be opened." << endl; } in.read( reinterpret_cast<char *>(&n1), sizeof(name) ); while ( !in.eof() ) { // display record cout<<endl<<"password at this index is:"<<n1.getpass()<<endl; cout<<"File pointer is at: "<<in.tellg()<<endl; // read next from file in.read( reinterpret_cast< char * >(&n1), sizeof(name)); } // end while } void name::readdata() { ifstream in("pass.txt",ios::binary); if ( !in ) { cout << "File could not be opened." << endl; } in.seekg((getid()-1)*sizeof(name)); //pointer moves to desired location where we have to read password according to its ID(index) cout<<"File pointer is at: "<<in.tellg()<<endl; in.read((char* )this,sizeof(name)); //reads from that pointed location cout<<endl<<"password at this index is:"<<getpass()<<endl; } int main() { name n1; cout<<"Enter 0 to write blank records"<<endl; cout<<"Enter 1 for new account"<<endl; cout<<"Enter 2 to login"<<endl; cout<<"Enter 3 to read all"<<endl; cout<<"Enter 9 to exit"<<endl; int option; cin>>option; while(option==0 || option==1 || option==2 || option==3) { if (option == 0) n1.writeBlank(); if(option==1) { /*int iD,p; cout<<"ID?"; cin>>iD; n1.setid(iD); cout<<"Enter password"; cin>>p; n1.setpass(p);*/ n1.writedata(); } int ind; if(option==2) { cout<<"Index?"; cin>>ind; n1.setid(ind); n1.readdata(); } if(option == 3) n1.readall(); cout<<"Enter 0 to write blank records"<<endl; cout<<"Enter 1 for new account"<<endl; cout<<"Enter 2 to login"<<endl; cout<<"Enter 3 to read all"<<endl; cout<<"Enter 9 to exit"<<endl; cin>>option; } } I Cant understand Y the previous records turn 0.

    Read the article

  • Caesar Cipher Program In C++ [migrated]

    - by xaliap81
    I am trying to write a caesar cipher program in c++. This is my codes template: int chooseKEY (){ //choose key shift from 1-26 } void encrypt (char * w, char *e, int key) { //Encryption function, *w is the text in the beginning, the *e is the encrypted text //Encryption in being made only in letters noy in numbers and punctuations // *e = *w + key } void decrypt (char * e, char *w, int key) { // Decryption function, *e is the text in the beginning, the *w is the decrypted text //Dencryption in being made only in letters no numbers and punctuations // *w = *e - key } void Caesar (char * inputFile, char * outputFile, int key, int mode) { // Read the inputfile which contains some data. If mode ==1 then the data is being //encrypted else if mode == 0 the data is being decrypted and is being written in //the output file } void main() { // call the Caesar function } The program has four functions, chooseKey function have to return an int as a shift key from 1-26. Encrypt function has three parameters, *w is the text in the beginning, *e is the encrypted text and the key is from the choosekey function.For encryption : Only letters have to be encrypted not numbers or punctuation and the letters are counting cyclic. Decrypt function has three parameters *e is the encrypted text, *w is the beginning text and the key. Caesar function has four parameters, inputfile which is the file that contains the beginning text, output file which contains the encrypted text, the key and the mode (if mode==1) encryption, (mode ==0) decryption. This is my sample code: #include <iostream> #include <fstream> using namespace std; int chooseKey() { int key_number; cout << "Give a number from 1-26: "; cin >> key_number; while(key_number<1 || key_number>26) { cout << "Your number have to be from 1-26.Retry: "; cin >> key_number; } return key_number; } void encryption(char *w, char *e, int key){ char *ptemp = w; while(*ptemp){ if(isalpha(*ptemp)){ if(*ptemp>='a'&&*ptemp<='z') { *ptemp-='a'; *ptemp+=key; *ptemp%=26; *ptemp+='A'; } } ptemp++; } w=e; } void decryption (char *e, char *w, int key){ char *ptemp = e; while(*ptemp){ if(isalpha(*ptemp)) { if(*ptemp>='A'&&*ptemp<='Z') { *ptemp-='A'; *ptemp+=26-key; *ptemp%=26; *ptemp+='a'; } } ptemp++; } e=w; } void Caesar (char *inputFile, char *outputFile, int key, int mode) { ifstream input; ofstream output; char buf, buf1; input.open(inputFile); output.open(outputFile); buf=input.get(); while(!input.eof()) { if(mode == 1){ encryption(&buf, &buf1, key); }else{ decryption(&buf1, &buf, key); } output << buf; buf=input.get(); } input.close(); output.close(); } int main(){ int key, mode; key = chooseKey(); cout << "1 or 0: "; cin >> mode; Caesar("test.txt","coded.txt",key,mode); system("pause"); } I am trying to run the code and it is being crashed (Debug Assertion Failed). I think the problem is somewhere inside Caesar function.How to call the encrypt and decrypt functions. But i don't know what exactly is. Any ideas?

    Read the article

  • Reading bmp file for steganography

    - by Shantanu Gupta
    I am trying to read a bmp file in C++(Turbo). But i m not able to print binary stream. I want to encode txt file into it and decrypt it. How can i do this. I read that bmp file header is of 54 byte. But how and where should i append txt file in bmp file. ? I know only Turbo C++, so it would be helpfull for me if u provide solution or suggestion related to topic for the same. int main() { ifstream fr; //reads ofstream fw; // wrrites to file char c; int random; clrscr(); char file[2][100]={"s.bmp","s.txt"}; fr.open(file[0],ios::binary);//file name, mode of open, here input mode i.e. read only if(!fr) cout<<"File can not be opened."; fw.open(file[1],ios::app);//file will be appended if(!fw) cout<<"File can not be opened"; while(!fr) cout<<fr.get(); // error should be here. but not able to find out what error is it fr.close(); fw.close(); getch(); } This code is running fine when i pass txt file in binary mode

    Read the article

  • RapidXML, reading and saving values

    - by Layne
    Hello, I've worked myself through the rapidXML sources and managed to read some values. Now I want to change them and save them to my XML file: Parsing file and set a pointer void SettingsHandler::getConfigFile() { pcSourceConfig = parsing->readFileInChar(CONF); cfg.parse<0>(pcSourceConfig); } Reading values from XML void SettingsHandler::getDefinitions() { SettingsHandler::getConfigFile(); stGeneral = cfg.first_node("settings")->value(); /* stGeneral = 60 */ } Changing values and saving to file void SettingsHandler::setDefinitions() { SettingsHandler::getConfigFile(); stGeneral = "10"; cfg.first_node("settings")->value(stGeneral.c_str()); std::stringstream sStream; sStream << *cfg.first_node(); std::ofstream ofFileToWrite; ofFileToWrite.open(CONF, std::ios::trunc); ofFileToWrite << "<?xml version=\"1.0\"?>\n" << sStream.str() << '\0'; ofFileToWrite.close(); } Reading file into buffer char* Parser::readFileInChar(const char* p_pccFile) { char* cpBuffer; size_t sSize; std::ifstream ifFileToRead; ifFileToRead.open(p_pccFile, std::ios::binary); sSize = Parser::getFileLength(&ifFileToRead); cpBuffer = new char[sSize]; ifFileToRead.read( cpBuffer, sSize); ifFileToRead.close(); return cpBuffer; } However, it's not possible to save the new value. My code is just saving the original file with a value of "60" where it should be "10". Rgds Layne

    Read the article

  • Need help modifying C++ application to accept continuous piped input in Linux

    - by GreeenGuru
    The goal is to mine packet headers for URLs visited using tcpdump. So far, I can save a packet header to a file using: tcpdump "dst port 80 and tcp[13] & 0x08 = 8" -A -s 300 | tee -a ./Desktop/packets.txt And I've written a program to parse through the header and extract the URL when given the following command: cat ~/Desktop/packets.txt | ./packet-parser.exe But what I want to be able to do is pipe tcpdump directly into my program, which will then log the data: tcpdump "dst port 80 and tcp[13] & 0x08 = 8" -A -s 300 | ./packet-parser.exe Here is the script as it is. The question is: how do I need to change it to support continuous input from tcpdump? #include <boost/regex.hpp> #include <fstream> #include <cstdio> // Needed to define ios::app #include <string> #include <iostream> int main() { // Make sure to open the file in append mode std::ofstream file_out("/var/local/GreeenLogger/url.log", std::ios::app); if (not file_out) std::perror("/var/local/GreeenLogger/url.log"); else { std::string text; // Get multiple lines of input -- raw std::getline(std::cin, text, '\0'); const boost::regex pattern("GET (\\S+) HTTP.*?[\\r\\n]+Host: (\\S+)"); boost::smatch match_object; bool match = boost::regex_search(text, match_object, pattern); if(match) { std::string output; output = match_object[2] + match_object[1]; file_out << output << '\n'; std::cout << output << std::endl; } file_out.close(); } } Thank you ahead of time for the help!

    Read the article

  • operator<< overload,

    - by mr.low
    //using namespace std; using std::ifstream; using std::ofstream; using std::cout; class Dog { friend ostream& operator<< (ostream&, const Dog&); public: char* name; char* breed; char* gender; Dog(); ~Dog(); }; im trying to overload the << operator. I'm also trying to practice good coding. But my code wont compile unless i uncomment the using namespace std. i keep getting this error and i dont know. im using g++ compiler. Dog.h:20: error: ISO C++ forbids declaration of ‘ostream’ with no type Dog.h:20: error: ‘ostream’ is neither function nor member function; cannot be declared friend. if i add line using std::cout; then i get this error. Dog.h:21: error: ISO C++ forbids declaration of ‘ostream’ with no type. Can somebody tell me the correct way to overload the << operator with out using namespace std;

    Read the article

  • Calling unmanaged dll from C#. Take 2

    - by Charles Gargent
    I have written a c# program that calls a c++ dll that echoes the commandline args to a file When the c++ is called using the rundll32 command it displays the commandline args no problem, however when it is called from within the c# it doesnt. I asked this question to try and solve my problem, but I have modified it my test environment and I think it is worth asking a new question. Here is the c++ dll #include "stdafx.h" #include "stdlib.h" #include <stdio.h> #include <iostream> #include <fstream> using namespace std; BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } extern "C" __declspec(dllexport) int WINAPI CMAKEX( HWND hwnd, HINSTANCE hinst, LPCSTR lpszCommandLine, DWORD dwReserved) { ofstream SaveFile("output.txt"); SaveFile << lpszCommandLine; SaveFile.close(); return 0; } Here is the c# app using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Net; namespace nac { class Program { [DllImport("cmakca.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CMAKEX(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow); static void Main(string[] args) { string cmdLine = @"/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"""; const int SW_SHOWNORMAL = 1; CMAKEX(IntPtr.Zero, IntPtr.Zero, cmdLine, SW_SHOWNORMAL).ToString(); } } } The output from the rundll32 command is rundll32 cmakex.dll,CMAKEX /source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp" /source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp" however the output when the c# app runs is /

    Read the article

  • LPCSTR, TCHAR, String

    - by user285327
    I am use next type of strings: LPCSTR, TCHAR, String i want to convert: 1) from TCHAR to LPCSTR 2) from String to char I convert from TCHAR to LPCSTR by that code: RunPath = TEXT("C:\\1"); LPCSTR Path = (LPCSTR)RunPath; From String to char i convert by that code: SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog; saveFileDialog1->Title = "?????????? ?????-????????"; saveFileDialog1->Filter = "bck files (*.bck)|*.bck"; saveFileDialog1->RestoreDirectory = true; pin_ptr<const wchar_t> wch = TEXT(""); if ( saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ) { wch = PtrToStringChars(saveFileDialog1->FileName); } else return; ofstream os(wch, ios::binary); My problem is that when i set "Configuration Properties - General Character Set in "Use Multi-Byte Character Set" the first part of code work correctly. But the second part of code return error C2440. When i set "Configuration Properties - General Character Set in "Use Unicode" the second part of code work correctly. But the first part of code return the only first character from TCHAR to LPCSTR.

    Read the article

  • DLL Exports: not all my functions are exported

    - by carmellose
    I'm trying to create a Windows DLL which exports a number of functions, howver all my functions are exported but one !! I can't figure it out. The macro I use is this simple one : __declspec(dllexport) void myfunction(); It works for all my functions except one. I've looked inside Dependency Walker and here they all are, except one. How can that be ? What would be the cause for that ? I'm stuck. Edit: to be more precise, here is the function in the .h : namespace my { namespace great { namespace namespaaace { __declspec(dllexport) void prob_dump(const char *filename, const double p[], int nx, const double Q[], const double xlow[], const char ixlow[], const double xupp[], const char ixupp[], const double A[], int my, const double bA[], const double C[], int mz, const double clow[], const char iclow[], const double cupp[], const char icupp[] ); }}} And in the .cpp file it goes like this: namespace my { namespace great { namespace namespaaace { namespace { void dump_mtx(std::ostream& ostr, const double *mtx, int rows, int cols, const char *ind = 0) { /* some random code there, nothing special, no statics whatsoever */ } } // end anonymous namespace here // dump the problem specification into a file void prob_dump( const char *filename, const double p[], int nx, const double Q[], const double xlow[], const char ixlow[], const double xupp[], const char ixupp[], const double A[], int my, const double bA[], const double C[], int mz, const double clow[], const char iclow[], const double cupp[], const char icupp[] ) { std::ofstream fout; fout.open(filename, std::ios::trunc); /* implementation there */ dump_mtx(fout, Q, nx, nx); } }}} Thanks

    Read the article

  • Why doesn't this for-loop execute?

    - by Maulrus
    I'm writing a program for an exercise that will read data from a file and format it to be readable. So far, I have a bit of code that will separate a header from the data that goes under it. Here it is: int main() { ifstream in("records.txt"); ofstream out("formatted_records.txt"); vector<string> temp; vector<string> headers; for (int i = 0; getline(in,temp[i]); ++i) { static int k = -1; if (str_isalpha(temp[i])) { headers[++k] = temp[i]; temp.erase(temp.begin() + i); } else { temp[i] += "," + headers[k]; } } } (str_isalpha() is just a function that applies isalpha() to every character in a string.) Now, the for-loop in this program doesn't execute, and I can't figure out why. Does anybody know?

    Read the article

  • Reading bmp file for encrypting and decrypting txt file into it

    - by Shantanu Gupta
    I am trying to read a bmp file in C++(Turbo). But i m not able to print binary stream. I want to encode txt file into it and decrypt it. How can i do this. I read that bmp file header is of 54 byte. But how and where should i append txt file in bmp file. ? I know only Turbo C++, so it would be helpfull for me if u provide solution or suggestion related to topic for the same. int main() { ifstream fr; //reads ofstream fw; // wrrites to file char c; int random; clrscr(); char file[2][100]={"s.bmp","s.txt"}; fr.open(file[0],ios::binary);//file name, mode of open, here input mode i.e. read only if(!fr) cout<<"File can not be opened."; fw.open(file[1],ios::app);//file will be appended if(!fw) cout<<"File can not be opened"; while(!fr) cout<<fr.get(); // error should be here. but not able to find out what error is it fr.close(); fw.close(); getch(); } This code is running fine when i pass txt file in binary mode

    Read the article

  • Help thinking "Pythony"

    - by Josh
    I'm brand new to Python and trying to learn it by replicating the following C++ function into python // determines which words in a vector consist of the same letters // outputs the words with the same letters on the same line void equivalentWords(vector <string> words, ofstream & outFile) { outFile << "Equivalent words\n"; // checkedWord is parallel to the words vector. It is // used to make sure each word is only displayed once. vector <bool> checkedWord (words.size(), false); for(int i = 0; i < words.size(); i++) { if (!checkedWord[i]){ outFile << " "; for(int j = i; j < words.size(); j++){ if(equivalentWords(words[i], words[j], outFile)) { outFile << words[j] << " "; checkedWord[j] = true; } } outFile << "\n"; } } } In my python code (below), rather than having a second vector, I have a list ("words") of lists of a string, a sorted list of the chars in the former string (because strings are immutable), and a bool (that tells if the word has been checked yet). However, I can't figure out how to change a value as you iterate through a list. for word, s_word, checked in words: if not checked: for word1, s_word1, checked1 in words: if s_word1 == s_word: checked1 = True # this doesn't work print word1, print "" Any help on doing this or thinking more "Pythony" is appreciated.

    Read the article

  • Can piping of screen to file change the result of a C++ code?

    - by Biga
    I am having this very weird behaviour with a C++ code: It gives me different results when running with and without piping the screen to a file (reproducible in cygwin and linux). I mean, if I get the same executable and run it like './run' or run it like './run out.log', I get different results! I use std::cout to output to screen, all lines ending with endl; I use ifstream for the input file; I use ofstream for output, all lines ending with endl. I am using g++ 4. Any idea what is going on? UPDATE: I have hard-coded the input data, so 'ifstream' is not used, and problem persists. UPDATE 2: That's getting interesting. I have output three variables that are computed initially, and that's what I get with and without piping direct to screen: 0 -0.02 0 piped: 0 -0.02 1.04083e-17 So there's a round-off difference with and without piping the output! Now, why piping would interefere with an internal computation of the code?

    Read the article

  • Can redirection of screen output to file change the result of a C++ code?

    - by Biga
    I am having this very weird behaviour with a C++ code: It gives me different results when running with and without redirecting the screen output to a file (reproducible in cygwin and linux). I mean, if I get the same executable and run it like ./run or run it like ./run >out.log, I get different results! I use std::cout to output to screen, all lines ending with endl; I use ifstream for the input file; I use ofstream for output, all lines ending with endl. I am using g++ 4. Any idea what is going on? UPDATE: I have hard-coded the input data, so 'ifstream' is not used, and problem persists. UPDATE 2: That's getting interesting. I have probed three variables that are computed initially, and that's what I get when using with and without redirecting the output to file redirected to file: 0 -0.02 0 direct to screen: 0 -0.02 1.04083e-17 So there's a round-off difference in the code variables with and without redirecting the output! Now, why redirecting would interefere with an internal computation of the code? UPDATE 3: If I redirect to /dev/null, I get the sam behaviour as outputing direct to screen, instead of redirecting to file.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >