Search Results

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

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

  • Ofstream writes empty file on linux

    - by commanderz
    Hi, I have a program which writes its output using ofstream. Everything works perfectly fine on Windows when compiled with Visual Studio, but it only writes empty file on Linux when compiled with GCC. ofstream out(path_out_cstr, ofstream::out); if(out.bad()){ cout << "Could not write the file" << flush; } else{ cout << "writing"; out << "Content" << endl; if(out.fail()) cout << "writing failed"; out.flush(); out.close(); } The directory which is being writen into has 0777 privileges. Thanks for help

    Read the article

  • Write set of integers to std::ofstream and be able to read them back

    - by bndu
    Hello, I need to write a bunch of unsigned integers to std::ofstream in binary mode: std::ofstream f; f.open("some path", std::ios::out | std::ios::binary); // some loop { unsigned int k = get_k(); // may product numbers from 0 to 65535 f << k; } f.close(); They are written to the output file "as is" w/o any delimiter. So when I'm trying to read them back (expecting to get what I wrote) using std::ifstream I get very strange values. What I'm doing wrong? Or I should to put ' ' (space) to the stream after any added number to separate them? Thanks.

    Read the article

  • C++ ofstream cannot write to file....

    - by user69514
    Hey I am trying to write some numbers to a file, but when I open the file it is empty. Can you help me out here? Thanks. /** main function **/ int main(){ /** variables **/ RandGen* random_generator = new RandGen; int random_numbers; string file_name; /** ask user for quantity of random number to produce **/ cout << "How many random number would you like to create?" << endl; cin >> random_numbers; /** ask user for the name of the file to store the numbers **/ cout << "Enter name of file to store random number" << endl; cin >> file_name; /** now create array to store the number **/ int random_array [random_numbers]; /** file the array with random integers **/ for(int i=0; i<random_numbers; i++){ random_array[i] = random_generator -> randInt(-20, 20); cout << random_array[i] << endl; } /** open file and write contents of random array **/ const char* file = file_name.c_str(); ofstream File(file); /** write contents to the file **/ for(int i=0; i<random_numbers; i++){ File << random_array[i] << endl; } /** close the file **/ File.close(); return 0; /** END OF PROGRAM **/ }

    Read the article

  • FileSystemWatcher does not fire when using C++ std::ofstream

    - by Adam Haile
    I'm trying to add a log monitor to an in-house test utility for a windows service I'm working on. The service is written in C++ (win32) and the utility is in .NET (C#) The log monitor works for many other C++ apps I've written, but not for my service. The only main difference I can see is that the other apps use the older ::WriteFile() to output to the log, whereas in the service I'm using std::ofstream like this: std::ofstream logFile; logFile.open("C:\\mylog.log"); logFile << "Hello World!" << std::endl; logFile.flush(); From my utility I use FileSystemWatcher like this: FileSystemWatcher fsw = new FileSystemWatcher(@"C:\", "mylog.log"); fsw.Changed += new FileSystemEventHandler(fsw_Handler); fsw.EnableRaisingEvents = true; But for the service, it never gets any change events as the log is updated. I've found that any example code using FileSystemWatcher I've come across online has the same exact issue as well... But, I know the events should be available because other log monitor apps (like BareTail) work fine with the service log file. I'd rather get the C# code for the utility to just work so it works with anything, but if I have to change the logging code for the service I will. Does anyone see what's going wrong here?

    Read the article

  • filebuf in ifstream and ofstream

    - by Juan
    How can i set a new char array to be the buffer of a fstream's filebuf, there is a function (setbuf) in the filebuf but it is protected. while searching on the web, some sites mention fstream::setbuf but it doesn't seem to exist anymore. Thanks

    Read the article

  • Any Alternate way for writing to a file other than ofstream

    - by Aditya
    Hi All, I am performing file operations (writeToFile) which fetches the data from a xml and writes into a output file(a1.txt). I am using MS Visual C++ 2008 and in windows XP. currently i am using this method of writing to output file.. 01.ofstreamhdr OutputFile; 02./* few other stmts / 03.hdrOutputFile.open(fileName, std::ios::out); 04. 05.hdrOutputFile << "#include \"commondata.h\""<< endl ; 06.hdrOutputFile << "#include \"Commonconfig.h\"" << endl ; 07.hdrOutputFile << "#include \"commontable.h\"" << endl << endl ; 08. hdrOutputFile << "#pragma pack(push,1)" << endl ; 09.hdrOutputFile << "typedef struct \n {" << endl ; 10./ simliar hdrOutputFiles statements... */.. I have around 250 lines to write.. Is any better way to perform this task. I want to reduce this hdrOutputFile and use a buffer to do this. Please guide me how to do that action. I mean, buff = "#include \"commontable.h\"" + "typedef struct \n {" + ....... hdrOutputFile << buff. is this way possible? Thanks Ramm

    Read the article

  • Strange error: cannot convert from 'int' to 'ios_base::openmode'

    - by Dylan Klomparens
    I am using g++ to compile some code. I wrote the following snippet: bool WriteAccess = true; string Name = "my_file.txt"; ofstream File; ios_base::open_mode Mode = std::ios_base::in | std::ios_base::binary; if(WriteAccess) Mode |= std::ios_base::out | std::ios_base::trunc; File.open(Name.data(), Mode); And I receive these errors... any idea why? Error 1: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’ Error 2: initializing argument 2 of ‘std::basic_filebuf<_CharT, _Traits* std::basic_filebuf<_CharT, _Traits::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits]’ As far as I could tell from a Google search, g++ is actually breaking the C++ standard here. Which I find quite astonishing, since they generally conform very strictly to the standard. Is this the case? Or am I doing something wrong. My reference for the standard: http://www.cplusplus.com/reference/iostream/ofstream/open/

    Read the article

  • c++ passing unknown type to a function and any Class type definition

    - by user259789
    I am trying to create a generic class to write and read Objects to/from file. Called it ActiveRecord class only has one method, which saves the class itself: void ActiveRecord::saveRecord(){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (this), sizeof(ActiveRecord)); stream.close(); } now I'm extending this class with User class: class User : public ActiveRecord { public: User(void); ~User(void); string name; string lastName; }; to create and save the user I would like to do something like: User user = User(); user.name = "John"; user.lastName = "Smith" user.save(); how can I get this ActiveRecord::saveRecord() method to take any object, and class definition so it writes whatever i send it: to look like: void ActiveRecord::saveRecord(foo_instance, FooClass){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (foo_instance), sizeof(FooClass)); stream.close(); } and while we're at it, what is the default Object type in c++. eg. in objective-c it's id in java it's Object in AS3 it's Object what is it in C++??

    Read the article

  • [c++] How to create a std::ofstream to a temp file?

    - by dehmann
    Okay, mkstemp is the preferred way to create a temp file in POSIX. But it opens the file and returns an int, which is a file descriptor. From that I can only create a FILE*, but not an std::ofstream, which I would prefer in C++. (Apparently, on AIX and some other systems, you can create an std::ofstream from a file descriptor, but my compiler complains when I try that.) I know I could get a temp file name with tmpnam and then open my own ofstream with it, but that's apparently unsafe due to race conditions, and results in a compiler warning (g++ v3.4. on Linux): warning: the use of `tmpnam' is dangerous, better use `mkstemp' So, is there any portable way to create an std::ofstream to a temp file?

    Read the article

  • Returning ifstream in a function

    - by wrongusername
    Here's probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function? Basically, I need to obtain the filename of a database from the user, and if the database with that filename does not exist, then I need to create that file for the user. I know how to do that, but only by asking the user to restart the program after creating the file. I wanted to avoid that inconvenience for the user if possible, but the function below does not compile in gcc: ifstream getFile() { string fileName; cout << "Please enter in the name of the file you'd like to open: "; cin >> fileName; ifstream first(fileName.c_str()); if(first.fail()) { cout << "File " << fileName << " not found.\n"; first.close(); ofstream second(fileName.c_str()); cout << "File created.\n"; second.close(); ifstream third(fileName.c_str()); return third; //compiler error here } else return first; } EDIT: sorry, forgot to tell you where and what the compiler error was: main.cpp:45: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here EDIT: I changed the function to return a pointer instead as Remus suggested, and changed the line in main() to "ifstream database = *getFile()"; now I get this error again, but this time in the line in main(): main.cpp:27: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here

    Read the article

  • C++ File manipulation problem

    - by Carlucho
    I am trying to open a file which normally has content, for the purpose of testing i will like to initialize the program without the files being available/existing so then the program should create empty ones, but am having issues implementing it. This is my code originally void loadFiles() { fstream city; city.open("city.txt", ios::in); fstream latitude; latitude.open("lat.txt", ios::in); fstream longitude; longitude.open("lon.txt", ios::in); while(!city.eof()){ city >> cityName; latitude >> lat; longitude >> lon; t.add(cityName, lat, lon); } city.close(); latitude.close(); longitude.close(); } I have tried everything i can think of, ofstream, ifstream, adding ios::out all all its variations. Could anybody explain me what to do in order to fix the problem. Thanks!

    Read the article

  • C++ - Unwanted characters printed in output file.

    - by Gabe
    This is the last part of the program I am working on. I want to output a tabular list of songs to cout. And then I want to output a specially formatted list of song information into fout (which will be used as an input file later on). Printing to cout works great. The problem is that tons of extra character are added when printing to fout. Any ideas? Here's the code: void Playlist::printFile(ofstream &fout, LinkedList<Playlist> &allPlaylists, LinkedList<Songs*> &library) { fout.open("music.txt"); if(fout.fail()) { cout << "Output file failed. Information was not saved." << endl << endl; } else { if(library.size() > 0) fout << "LIBRARY" << endl; for(int i = 0; i < library.size(); i++) // For Loop - "Incremrenting i"-Loop to go through library and print song information. { fout << library.at(i)->getSongName() << endl; // Prints song name. fout << library.at(i)->getArtistName() << endl; // Prints artist name. fout << library.at(i)->getAlbumName() << endl; // Prints album name. fout << library.at(i)->getPlayTime() << " " << library.at(i)->getYear() << " "; fout << library.at(i)->getStarRating() << " " << library.at(i)->getSongGenre() << endl; } if(allPlaylists.size() <= 0) fout << endl; else if(allPlaylists.size() > 0) { int j; for(j = 0; j < allPlaylists.size(); j++) // Loops through all playlists. { fout << "xxxxx" << endl; fout << allPlaylists.at(j).getPlaylistName() << endl; for(int i = 0; i < allPlaylists.at(j).listSongs.size(); i++) { fout << allPlaylists.at(j).listSongs.at(i)->getSongName(); fout << endl; fout << allPlaylists.at(j).listSongs.at(i)->getArtistName(); fout << endl; } } fout << endl; } } } Here's a sample of the output to music.txt (fout): LIBRARY sadljkhfds dfgkjh dfkgh 3 3333 3 Rap sdlkhs kjshdfkh sdkjfhsdf 3 33333 3 Rap xxxxx PayröÈöè÷÷(÷H÷h÷÷¨÷È÷èøø(øHøhøø¨øÈøèùù(ùHùhùù¨ùÈùèúú(úHúhúú¨úÈúèûû(ûHûhûû¨ûÈûèüü(üHühüü¨üÈüèýý(ýHýhý ! sdkjfhsdf!õüöýÄõ¼5! sadljkhfds!þõÜö|ö\ þx þ  þÈ þð ÿ ÿ@ ÿh ÿ ÿ¸ ÿà 0 X ¨ Ð ø enter code here enter code here

    Read the article

  • C++ iostream not setting eof bit even if gcount returns 0

    - by raph.amiard
    Hi I'm developping an application under windows, and i'm using fstreams to read and write to the file. I'm writing with fstream opened like this : fs.open(this->filename.c_str(), std::ios::in|std::ios::out|std::ios::binary); and writing with this command fs.write(reinterpret_cast<char*>(&e.element), sizeof(T)); closing the file after each write with fs.close() Reading with ifstream opened like this : is.open(filename, std::ios::in); and reading with this command : is.read(reinterpret_cast<char*>(&e.element), sizeof(T)); The write is going fine. However, i read in a loop this way : while(!is.eof()) { is.read(reinterpret_cast<char*>(&e.element), sizeof(T)); } and the program keeps reading, even though the end of file should be reached. istellg pos is 0, and gcount is equal to 0 too, but the fail bit and eof bit are both ok. I'm running crazy over this, need some help ...

    Read the article

  • How do you search a document for a string in c++?

    - by Jeff
    Here's my code so far: #include<iostream> #include<string> #include<fstream> using namespace std; int main() { int count = 0; string fileName; string keyWord; string word; cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ; getline(cin, fileName); cout << endl; cout << "Please input the word you'd like to search for: " << endl; cin >> keyWord; cout << endl; ifstream infile(fileName.c_str()); while(infile.is_open()) { getline(cin,word); if(word == keyWord) { cout << word << endl; count++; } if(infile.eof()) { infile.close(); } } cout << count; } I'm not sure how to go to the next word, currently this infinite loops...any recommendation? Also...how do I tell it to print out the line that that word was on? Thanks in advance!

    Read the article

  • how do i make maximum minimum and average score statistic in this code? [on hold]

    - by goldensun player
    i wanna out put the maximum minimum and average score as a statistic category under the student ids and grades in the output file. how do i do that? here is the code: #include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <assert.h> using namespace std; int openfiles(ifstream& infile, ofstream& outfile); void Size(ofstream&, int, string); int main() { int num_student = 4, count, length, score2, w[6]; ifstream infile, curvingfile; char x; ofstream outfile; float score; string key, answer, id; do { openfiles(infile, outfile); // function calling infile >> key; // answer key for (int i = 0; i < num_student; i++) // loop over each student { infile >> id; infile >> answer; count = 0; length = key.size(); // length represents number of questions in exam from exam1.dat // size is a string function.... Size (outfile, length, answer); for (int j = 0; j < length; j++) // loop over each question { if (key[j] == answer[j]) count++; } score = (float) count / length; score2 = (int)(score * 100); outfile << id << " " << score2 << "%"; if (score2 >= 90)//<-----w[0] outfile << "A" << endl; else if (score2 >= 80)//<-----w[1] outfile << "B" << endl; else if (score2 >= 70)//<-----w[2] outfile << "C" << endl; else if (score2 >= 60)//<-----w[3] outfile << "D" << endl; else if (score2 >= 50)//<-----w[4] outfile << "E" << endl; else if (score2 < 50)//<-----w[5] outfile << "F" << endl; } cout << "Would you like to attempt a new trial? (y/n): "; cin >> x; } while (x == 'y' || x == 'Y'); return 0; } int openfiles(ifstream& infile, ofstream& outfile) { string name1, name2, name3, answerstring, curvedata; cin >> name1; name2; name3; if (name1 == "exit" || name2 == "exit" || name3 == "exit" ) return false; cout << "Input the name for the exam file: "; cin >> name1; infile.open(name1.c_str()); infile >> answerstring; cout << "Input the name for the curving file: "; cin >> name2; infile.open(name2.c_str()); infile >> curvedata; cout << "Input the name for the output: "; cin >> name3; outfile.open(name3.c_str()); return true; } void Size(ofstream& outfile, int length, string answer) { bool check;// extra answers, lesser answers... if (answer.size() > length) { outfile << "Unnecessary extra answers"; } else if (answer.size() < length) { outfile << "The remaining answers are incorrect"; } else { check = false; }; } and how do i use assert for preconditions and post conditional functions? i dont understand this that well...

    Read the article

  • Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++

    - by mgj
    Hi...:) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried using the ord() function in python to check if the text contains any Unicode characters( non ascii characters) apart from the ascii ones.. I found quite a number of them. I have a strong feeling that this could be due to the original text itself( The INPUT ). Input-File: Just copy paste it into a file "acle5v1.txt" The objective of this code below is to check for upper case characters and to convert it to lower case and also to remove all punctuations so that these words are taken for further processing for word alignment #include<iostrea> #include<fstream> #include<ctype.h> #include<cstring> using namespace std; ifstream fin2("acle5v1.txt"); ofstream fin3("acle5v1_op.txt"); ofstream fin4("chkcharadded.txt"); ofstream fin5("chkcharntadded.txt"); ofstream fin6("chkprintchar.txt"); ofstream fin7("chknonasci.txt"); ofstream fin8("nonprinchar.txt"); int main() { char ch,ch1; fin2.seekg(0); fin3.seekp(0); int flag = 0; while(!fin2.eof()) { ch1=ch; fin2.get(ch); if (isprint(ch))// if the character is printable flag = 1; if(flag) { fin6<<"Printable character:\t"<<ch<<"\t"<<(int)ch<<endl; flag = 0; } else { fin8<<"Non printable character caught:\t"<<ch<<"\t"<<int(ch)<<endl; } if( isalnum(ch) || ch == '@' || ch == ' ' )// checks for alpha numeric characters { fin4<<"char added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl; if(isupper(ch)) { //tolower(ch); fin3<<(char)tolower(ch); } else { fin3<<ch; } } else if( ( ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 != ' ' ) { fin3<<' '; } else if( (ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 == ' ' ) { //fin3<<" '; } else if( !(int(ch)>=0 && int(ch)<=127) ) { fin5<<"Char of ascii within range not added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl; } else { fin7<<"Non ascii character caught(could be a -ve value also)\t"<<ch<<int(ch)<<endl; } } return 0; } I have a similar code as the above written in python which gives me an otput which is again not readable and not editable The code in python looks like this: #!/usr/bin/python # -*- coding: UTF-8 -*- import sys input_file=sys.argv[1] output_file=sys.argv[2] list1=[] f=open(input_file) for line in f: line=line.strip() #line=line.rstrip('.') line=line.replace('.','') line=line.replace(',','') line=line.replace('#','') line=line.replace('?','') line=line.replace('!','') line=line.replace('"','') line=line.replace('?','') line=line.replace('|','') line = line.lower() list1.append(line) f.close() f1=open(output_file,'w') f1.write(' '.join(list1)) f1.close() the file takes ip and op at runtime.. as: python punc_remover.py acle5v1.txt acle5v1_op.txt The output of this file is in "acle5v1_op.txt" now after processing this particular output file is needed for further processing. This particular file "aclee5v1_op.txt" is the UNREADABLE Aand UNEDITABLE File that I am not being able to use for further processing. I need this for Word alignment in NLP. I tried readin this output with the following program #include<iostream> #include<fstream> using namespace std; ifstream fin1("acle5v1_op.txt"); ofstream fout1("chckread_acle5v1_op.txt"); ofstream fout2("chcknotread_acle5v1_op.txt"); int main() { char ch; int flag = 0; long int r = 0; long int nr = 0; while(!(fin1)) { fin1.get(ch); if(ch) { flag = 1; } if(flag) { fout1<<ch; flag = 0; r++; } else { fout2<<"Char not been able to be read from source file\n"; nr++; } } cout<<"Number of characters able to be read: "<<r; cout<<endl<<"Number of characters not been able to be read: "<<nr; return 0; } which prints the character if its readable and if not it doesn't print them but I observed the output of both the file is blank thus I could draw a conclusion that this file "acle5v1_op.txt" is UNREADABLE AND UNEDITABLE. Could you please help me on how to deal with this problem.. To tell you a bit about the statistics wrt the original input file "acle5v1.txt" file it has around 3441 lines in it and around 3 million characters in it. Keeping in mind the number of characters in the file you editor might/might not be able to manage to open the file.. I was able to open the file in gedit of Fedora 10 which I am currently using .. This is just to notify you that opening with a particular editor was not actually an issue at least in my case... Can I use scripting languages like Python and Perl to deal with this problem if Yes how? could please be specific on that regard as I am a novice to Perl and Python. Or could you please tell me how do I solve this problem using C++ itself.. Thank you...:) I am really looking forward to some help or guidance on how to go about this problem....

    Read the article

  • Is there any need for me to use wstring in the following case

    - by Yan Cheng CHEOK
    Currently, I am developing an app for a China customer. China customer are mostly switch to GB2312 language in their OS encoding. I need to write a text file, which will be encoded using GB2312. I use std::ofstream file I compile my application under MBCS mode, not unicode. I use the following code, to convert CString to std::string, and write it to file using ofstream std::string Utils::ToString(CString& cString) { /* Will not work correctly, if we are compiled under unicode mode. */ return (LPCTSTR)cString; } To my surprise. It just works. I thought I need to at least make use of wstring. I try to do some investigation. Here is the MBCS.txt generated. I try to print a single character named ? (its value is 0xBDC5) When I use CString to carry this character, its length is 2. When I use Utils::ToString to perform conversion to std::string, the returned string length is 2. I write to file using std::ofstream My question is : When I exam MBCS.txt using a hex editor, the value is displayed as BD (LSB) and C5 (MSB). But I am using little endian machine. Isn't hex editor should show me C5 (LSB) and BD (MSB)? I check from wikipedia. GB2312 seems doesn't specific endianness. It seems that using std::string + CString just work fine for my case. May I know in what case, the above methodology will not work? and when I should start to use wstring?

    Read the article

  • "Expected initializer before '<' token" in header file

    - by Sarah
    I'm pretty new to programming and am generally confused by header files and includes. I would like help with an immediate compile problem and would appreciate general suggestions about cleaner, safer, slicker ways to write my code. I'm currently repackaging a lot of code that used to be in main() into a Simulation class. I'm getting a compile error with the header file for this class. I'm compiling with gcc version 4.2.1. // Simulation.h #ifndef SIMULATION_H #define SIMULATION_H #include <cstdlib> #include <iostream> #include <cmath> #include <string> #include <fstream> #include <set> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/composite_key.hpp> #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/tuple/tuple_io.hpp> #include "Parameters.h" #include "Host.h" #include "rng.h" #include "Event.h" #include "Rdraws.h" typedef multi_index_container< // line 33 - first error boost::shared_ptr< Host >, indexed_by< hashed_unique< const_mem_fun<Host,int,&Host::getID> >, // 0 - ID index ordered_non_unique< tag<age>,const_mem_fun<Host,int,&Host::getAgeInY> >, // 1 - Age index hashed_non_unique< tag<household>,const_mem_fun<Host,int,&Host::getHousehold> >, // 2 - Household index ordered_non_unique< // 3 - Eligible by age & household tag<aeh>, composite_key< Host, const_mem_fun<Host,int,&Host::getAgeInY>, const_mem_fun<Host,bool,&Host::isEligible>, const_mem_fun<Host,int,&Host::getHousehold> > >, ordered_non_unique< // 4 - Eligible by household (all single adults) tag<eh>, composite_key< Host, const_mem_fun<Host,bool,&Host::isEligible>, const_mem_fun<Host,int,&Host::getHousehold> > >, ordered_non_unique< // 5 - Household & age tag<ah>, composite_key< Host, const_mem_fun<Host,int,&Host::getHousehold>, const_mem_fun<Host,int,&Host::getAgeInY> > > > // end indexed_by > HostContainer; typedef std::set<int> HHSet; class Simulation { public: Simulation( int sid ); ~Simulation(); // MEMBER FUNCTION PROTOTYPES void runDemSim( void ); void runEpidSim( void ); void ageHost( int id ); int calcPartnerAge( int a ); void executeEvent( Event & te ); void killHost( int id ); void pairHost( int id ); void partner2Hosts( int id1, int id2 ); void fledgeHost( int id ); void birthHost( int id ); void calcSI( void ); double beta_ij_h( int ai, int aj, int s ); double beta_ij_nh( int ai, int aj, int s ); private: // SIMULATION OBJECTS double t; double outputStrobe; int idCtr; int hholdCtr; int simID; RNG rgen; HostContainer allHosts; // shared_ptr to Hosts - line 102 - second error HHSet allHouseholds; int numInfecteds[ INIT_NUM_AGE_CATS ][ INIT_NUM_STYPES ]; EventPQ currentEvents; // STREAM MANAGEMENT void writeOutput(); void initOutput(); void closeOutput(); std::ofstream ageDistStream; std::ofstream ageDistTStream; std::ofstream hhDistStream; std::ofstream hhDistTStream; std::string ageDistFile; std::string ageDistTFile; std::string hhDistFile; std::string hhDistTFile; }; #endif I'm hoping the other files aren't so relevant to this problem. When I compile with g++ -g -o -c a.out -I /Applications/boost_1_42_0/ Host.cpp Simulation.cpp rng.cpp main.cpp Rdraws.cpp I get Simulation.h:33: error: expected initializer before '<' token Simulation.h:102: error: 'HostContainer' does not name a type and then a bunch of other errors related to not recognizing the HostContainer. It seems like I have all the right Boost #includes for the HostContainer to be understood. What else could be going wrong? I would appreciate immediate suggestions, troubleshooting tips, and other advice about my code. My plan is to create a "HostContainer.h" file that includes the typedef and structs that define its tags, similar to what I'm doing in "Event.h" for the EventPQ container. I'm assuming this is legal and good form.

    Read the article

  • Having an issue with overwriting an element of a file correctly (numeric)

    - by IngeniousHax
    This is an ATM style program, but currently it doesn't do exactly what I need it to do... I need to get the current balance, and when money is transferred from either checking or savings, it should add it to checking and subtract it from savings. which is does, but not correctly... Input example -=[ Funds Transfer ]=- -=[ Savings to Checking ]=- Account Name: nomadic Amount to transfer: $400 New Balance in Checking: $900 // original was 500 New Balance in Savings: $7.7068e+012 // this should now be 1100... Here is my code, it's a lot of code, but there are no errors, so throwing it into an IDE and compiling should be fairly quick for whoever would like to help. mainBankClass.h mainBankClass.h #ifndef MAINBANKCLASS_H #define MAINBANKCLASS_H #include <iostream> #include <fstream> #include <string> using namespace std; class Banking { protected: string checkAcctName, saveAcctName; // Name on the account int acctNumber[13]; // Account number float acctBalance, initSaveDeposit, initCheckDeposit, depAmt; // amount in account, and amount to deposit public: char getBalanceChoice(); // Get name on account for displaying relevant information char newAccountMenu(); // Create a new account and assign it a random account number void invalid(char *); // If an invalid option is chosen char menu(); // Print the main menu for the user. virtual float deposit(){ return 0; } // virtual function for deposits // virtual float withdrawal() = 0; // Virtual function for withdrawals void fatal(char *); // Handles fatal errors. Banking(); }; class Checking : public Banking { public: friend ostream operator<<(ostream &, Checking &); friend istream operator>>(istream &, Checking &); Checking operator <= (const Checking &) const; void newCheckingAccount(); void viewCheckingBalance(); void transferFromSaving(); float deposit() { return (acctBalance += depAmt); } }; class Saving : public Banking { public: friend ostream &operator<<(ostream &, Saving &); friend istream &operator>>(istream &, Saving &); Saving operator <= (const Saving &) const; void newSavingAccount(); void viewSavingBalance(); void transferFromChecking(); float deposit() { return (acctBalance += depAmt); } }; class checkAndSave : public Banking { public: void newCheckAndSave(); void viewBothBalances(); }; #endif bankAccount.cpp #include <iostream> #include <sstream> #include <string> #include <iomanip> #include <fstream> #include <time.h> #include "MainBankClass.h" /*****************************\ | BANKING CONSTRUCTOR | \*****************************/ Banking::Banking() { string acctName; // Name on the account acctNumber[13] = 0; // Account number acctBalance = 0; initCheckDeposit = 0; initSaveDeposit = 0; depAmt = 0; }; /********************************\ | The following code is to print the menu | | and recieve the users choice on what | | they want to do with the ATM | \********************************/ char Banking::menu() { char choice; system("cls"); cout << "\t\t -=[ Main Menu ]=- \n\n" << "\tA) Create New Account\n" << "\tB) View Account Balance\n" << "\tC) Transfer Funds From Checking To Savings\n" << "\tD) Transfer Funds From Savings To Checking\n" << "\tE) Exit\n" << "\n\n\tSelection: "; cin >> choice; cin.ignore(); choice = toupper(choice); while(!isalpha(choice)) { invalid("[!!] Invalid selection.\n[!!] Choose a valid option: "); cin >> choice; cin.ignore(); } return choice; } /*********************\ | Will read in account choic | | and display it for the user | \*********************/ char Banking::getBalanceChoice() { char choice; fstream saveFile("saving.dat", ios::in | ios::beg); system("cls"); cout << "\t\t -=[ View Account Balance ]=-\n\n"; cout << "A) View Checking Account\n" << "B) View Saving Account\n" << "C) View Checking \\ Saving Account\n" << endl; cout << "Choice: "; cin >> choice; choice = toupper(choice); if(!isalpha(choice)) fatal(" [!!] Invalid Choice"); return choice; } /***************************\ | Incase an invalid decision to made | | this throws the error message sent | | to it by the calling area | \***************************/ void Banking::invalid(char *msg) { cout << msg; } /*************************\ | Used if files can not be opened | | and exits with code 251: | | miscommunication with server | \*************************/ void Banking::fatal(char *msg) { cout << msg; exit(1); } /***************************\ | Create an account, either checking | | or savings, or both. | | Must should create a randomly | | generated account number that will | | correspond with each account. | \***************************/ /************************\ NOTE:: WILL BE UPDATED TO CONTAIN A PIN FOR ACCOUNT VERIFICATION *************************/ char Banking::newAccountMenu() { srand(time(NULL)); // Seed random generator with time initialized to NULL char acctChoice; // choice for the account type ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts system("cls"); cout << "\t\t-=[ New Account Creation ]=-\n\n" << endl; cout << "A) Checking Account\n" << "B) Savings Account\n" << "C) Checking and Saving Account\n" << endl; cout << "New account type: "; cin >> acctChoice; acctChoice = toupper(acctChoice); cin.clear(); cin.sync(); return acctChoice; } /********************************************************************* ********************************************************************** CHECKING ACCOUNT CODE ********************************************************************** **********************************************************************/ // New Checking Account Creation void Checking::newCheckingAccount() { system("cls"); ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts cout << "\t\t -=[ New Checking Account ]=- \n" << endl; cout << "Name of the main holder to be on the account: "; getline(cin, checkAcctName); cout << "Initial deposit amount: $"; cin >> initCheckDeposit; if(initCheckDeposit <= 0) { while(initCheckDeposit <= 0) { invalid("[!!] 0 or negative amount entered\nMaybe a typo?\n"); cout << "Deposit Amount: $"; cin >> initCheckDeposit; } } if(!checkFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); checkFile << checkAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); // Build a random checking account number checkFile << acctNumber[j]; } checkFile << endl; checkFile << initCheckDeposit << endl; checkFile.close(); } void Checking::viewCheckingBalance() { fstream checkFile("checking.dat", ios::in | ios::beg); string name; int i = 0; double balance = 0; system("cls"); cout << "\t\t -=[ View Checking Account ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } if(name == checkAcctName) { system("cls"); cout << "\t\t -=[ Checking Account Balance ]=-\n\n" << endl; cout << "Account Name: " << checkAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; checkFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } else fatal("[!!] Invalid Account\n"); checkFile.close(); getchar(); } void Checking::transferFromSaving() // Move funds FROM SAVINGS to CHECKING { system("cls"); string name; long checkPos = 0; long savePos = 0; float savingBalance = 0; string saveAcctName; int i = 0; cin.clear(); fstream saveFile("saving.dat", ios::in | ios::out | ios::beg); fstream checkFile("checking.dat", ios::in | ios::out | ios::beg); cout << "\t\t-=[ Funds Transfer ]=-" << endl; cout << "\t\t-=[ Savings to Checking ]=-" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i = 0; i++; getline(saveFile, saveAcctName); } if(name == checkAcctName) { cout << "Amount to transfer: $"; float depAmt = 0; cin >> depAmt; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; } checkPos = checkFile.tellg(); // if the file is found, get the position of acctBalance and store it in ptrPos checkFile.seekg(checkPos); checkFile >> acctBalance; savePos = saveFile.tellg(); saveFile.seekg(savePos); // sending the cursor in the file to ptrPos + 1 to ignore white space saveFile >> savingBalance; if(savingBalance < depAmt) // if checking account does not have enough funds, exit with NSF code fatal("[!!] Insufficient Funds\n"); acctBalance += depAmt; // can be changed to an overloaded operator savingBalance -= depAmt; // can be changed to an overloaded operator checkFile.seekp(checkPos); // go to position previously set above checkFile << acctBalance; // write new balance to checkFile saveFile.seekp(savePos); // same thing as above comment saveFile << savingBalance; // write new balance to saveFile cout << "New Balance in Checking: $" << acctBalance << endl; // will be removed later cout << "New Balance in Savings: $" << savingBalance << endl; // will be removed later aswell } else fatal("[!!] Linked accounts do not exist.\n"); // if account is not found saveFile.close(); checkFile.close(); } /******************************************************** ******************************************************** SAVING ACCOUNT CODE ********************************************************* *********************************************************/ void Saving::newSavingAccount() { system("cls"); ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts cout << "\t\t -=[ New Savings Account ]=- \n" << endl; cout << "Name of the main holder to be on account: "; getline(cin, saveAcctName); cout << "Deposit Amount: $"; cin >> initSaveDeposit; if(initSaveDeposit <= 0) { while(initSaveDeposit <= 0) { invalid("[!!]0 or negative value entered.\nPerhaps a typo?\n"); cout << "Deposit amount: $"; cin >> initSaveDeposit; } } if(!saveFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); saveFile << saveAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); saveFile << acctNumber[j]; } saveFile << endl; saveFile << initSaveDeposit << endl; saveFile.close(); } void Saving::viewSavingBalance() { string name; int i = 0; fstream saveFile("saving.dat", ios::in | ios::beg); cin.clear(); system("cls"); cout << "\t\t -=[ View Saving Account ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i++; getline(saveFile, saveAcctName); } if(name == saveAcctName) { system("cls"); cout << "\t\t -=[ Saving Account Balance ]=-\n\n" << endl; cout << "Account Name: " << saveAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; saveFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } else fatal("[!!] Invalid Account\n"); saveFile.close(); getchar(); } // NEED TO WORK ON THIS PORTION TOMORROW AND MONDAY, ADD OVERLOADED OPS FOR ASSIGNMENT!!!!!!! void Saving::transferFromChecking() // This is to take money FROM checking and ADD IT TO SAVING { system("cls"); string name; long savePos = 0; long checkPos = 0; float checkingBalance = 0; string checkAcctName; int i = 0; cin.clear(); fstream saveFile("saving.dat", ios::in | ios::out | ios::beg); fstream checkFile("checking.dat", ios::in | ios::out | ios::beg); cout << "\t\t-=[ Funds Transfer ]=-" << endl; cout << "\t\t-=[ Checking to Savings ]=-" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(saveFile, saveAcctName); getline(checkFile, checkAcctName); while(name != saveAcctName && name != checkAcctName && !saveFile.fail() && !checkFile.fail()) { i++; getline(saveFile, saveAcctName); getline(checkFile, checkAcctName); } if(name == saveAcctName) { cout << "Amount to transfer: $"; float depAmt = 0; cin >> depAmt; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; } savePos = saveFile.tellg(); // if the file is found, get the position of acctBalance and store it in ptrPos saveFile.seekg(savePos); saveFile >> acctBalance; checkPos = checkFile.tellg(); checkFile.seekg(checkPos); // if file is found, store current position of the cursor to ptrPos checkFile >> checkingBalance; if(checkingBalance < depAmt) // if checking account does not have enough funds, exit with NSF code fatal("[!!] Insufficient Funds\n"); // Can also place overloaded op here acctBalance += depAmt; // can be changed to an overloaded operator checkingBalance -= depAmt; // can be changed to an overloaded operator saveFile.seekg(savePos); // go to position previously set above saveFile << acctBalance; // write new balance to saveFile checkFile.seekg(checkPos); // same thing as above comment checkFile << checkingBalance; // write new balance to checkFile cout << "New Balance in Savings: $" << acctBalance << endl; // will be removed later cout << "New Balance in Checking: $" << checkingBalance << endl; // will be removed later aswell } else fatal("[!!] Linked accounts do not exist.\n"); // if account is not found saveFile.close(); checkFile.close(); } /******************************************** ******************************************** CHECK AND SAVE CODE ********************************************** **********************************************/ void checkAndSave::newCheckAndSave() { system("cls"); ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts cout << "\t -=[ New Checking & Saving Account ]=- \n" << endl; cout << "Name of the main holder to be on account: "; getline(cin, checkAcctName); saveAcctName = checkAcctName; cout << "Checking Deposit Amount: $"; cin >> initCheckDeposit; if(initCheckDeposit <= 0) { while(initCheckDeposit <= 0) { invalid("[!!] 0 or negative amount entered\nMaybe a typo?\n"); cout << "Deposit Amount: $"; cin >> initCheckDeposit; } } cout << "Saving Deposit Amount: $"; cin >> initSaveDeposit; if(initSaveDeposit <= 0) { while(initSaveDeposit <= 0) { invalid("[!!]0 or negative value entered.\nPerhaps a typo?\n"); cout << "Deposit amount: $"; cin >> initSaveDeposit; } } if(!saveFile || !checkFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); checkFile << checkAcctName << endl; saveFile << saveAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); checkFile << acctNumber[j]; saveFile << acctNumber[j]; } saveFile << endl; saveFile << initSaveDeposit << endl; checkFile << endl; checkFile << initCheckDeposit << endl; checkFile.close(); saveFile.close(); } void checkAndSave::viewBothBalances() { string name; int i = 0; fstream checkFile("checking.dat", ios::in | ios::beg); fstream saveFile("saving.dat", ios::in | ios::beg); system("cls"); cin.clear(); cout << "\t-=[ Saving & Checking Account Balance ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); saveAcctName = name; /**********************\ | Checking Account portion | | of the checking & savings | | overview | \**********************/ while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } system("cls"); if(name != checkAcctName && checkFile.fail()) invalid("\n\n[!!] No Checking Account Found\n"); cout << "\t\t -=[ Checking Account ]=- \n" << endl; cout << "Account Name: " << checkAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; checkFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; /*********************\ | Saving Account portion | | of the checking & saving | | overview | \*********************/ getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i++; getline(saveFile, saveAcctName); } if(name != saveAcctName && saveFile.fail()) invalid("\n\n[!!] No Saving Account Found\n"); if(name == saveAcctName) { cout << "\t\t -=[ Saving Account ]=-\n\n" << endl; cout << "Account Name: " << saveAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; saveFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } if(name != saveAcctName && name != checkAcctName && saveFile.fail() && checkFile.fail()) fatal("[!!] No Accounts Have Been Found\n"); checkFile.close(); saveFile.close(); getchar(); } Main.cpp #include <iostream> #include "MainBankClass.h" using namespace std; int main() { Banking bank; Checking check; Saving save; checkAndSave CanS; char choice; choice = bank.menu(); // Call the banking menu switch(choice) { case 'A': choice = bank.newAccountMenu(); switch(choice) { case 'A': check.newCheckingAccount(); break; case 'B': save.newSavingAccount(); break; case 'C': CanS.newCheckAndSave(); break; default: system("cls"); bank.fatal("[!!] Invalid option\n"); break; } break; /***********************************************/ case 'B': choice = bank.getBalanceChoice(); switch(choice) { case 'A': check.viewCheckingBalance(); break; case 'B': save.viewSavingBalance(); break; case 'C': CanS.viewBothBalances(); break; default: bank.fatal("Invalid decision\n"); break; } /*************************************************/ break; case 'C': check.transferFromSaving(); break; case 'D': save.transferFromChecking(); break; case 'E': system("cls"); cout << "\t\t-=[ Disconnecting From System ]=-\n"; cout << "\t\t\t Thank you" << endl; cout << "\t\t Have a nice day!" << endl; exit(1); break; default: system("cls"); bank.invalid("\n\n\n\n\t\t [+] Invalid Selection \n\t\t[+] Disconnecting From System \n\t\t\tGood-bye \n\n\n\n\n\n\n"); exit(1); break; } return 0; }

    Read the article

  • Steganography : Encoded audio and video file not being played, getting corrupted. What is the issue

    - by Shantanu Gupta
    I have made a steganography program to encrypt/Decrypt some text under image audio and video. I used image as bmp(54 byte header) file, audio as wav(44 byte header) file and video as avi(56 byte header) file formats. When I tries to encrypt text under all these file then it gets encrypted successfully and are also getting decrypted correctly. But it is creating a problem with audio and video i.e these files are not being played after encrypted result. What can be the problem. I am working on Turbo C++ compiler. I know it is super outdated compiler but I have to do it in this only. Here is my code to encrypt. int Binary_encode(char *txtSourceFileName, char *binarySourceFileName, char *binaryTargetFileName,const short headerSize) { long BinarySourceSize=0,TextSourceSize=0; char *Buffer; long BlockSize=10240, i=0; ifstream ReadTxt, ReadBinary; //reads ReadTxt.open(txtSourceFileName,ios::binary|ios::in);//file name, mode of open, here input mode i.e. read only if(!ReadTxt) { cprintf("\nFile can not be opened."); return 0; } ReadBinary.open(binarySourceFileName,ios::binary|ios::in);//file name, mode of open, here input mode i.e. read only if(!ReadBinary) { ReadTxt.close();//closing opened file cprintf("\nFile can not be opened."); return 0; } ReadBinary.seekg(0,ios::end);//setting pointer to a file at the end of file. ReadTxt.seekg(0,ios::end); BinarySourceSize=(long )ReadBinary.tellg(); //returns the position of pointer TextSourceSize=(long )ReadTxt.tellg(); //returns the position of pointer ReadBinary.seekg(0,ios::beg); //sets the pointer to the begining of file ReadTxt.seekg(0,ios::beg); //sets the pointer to the begining of file if(BinarySourceSize<TextSourceSize*50) //Minimum size of an image should be 50 times the size of file to be encrypted { cout<<"\n\n"; cprintf("Binary File size should be bigger than text file size."); ReadBinary.close(); ReadTxt.close(); return 0; } cout<<"\n"; cprintf("\n\nSize of Source Image/Audio File is : "); cout<<(float)BinarySourceSize/1024; cprintf("KB"); cout<<"\n"; cprintf("Size of Text File is "); cout<<TextSourceSize; cprintf(" Bytes"); cout<<"\n"; getch(); //write header to file without changing else file will not open //bmp image's header size is 53 bytes Buffer=new char[headerSize]; ofstream WriteBinary; // writes to file WriteBinary.open(binaryTargetFileName,ios::binary|ios::out|ios::trunc);//file will be created or truncated if already exists ReadBinary.read(Buffer,headerSize);//reads no of bytes and stores them into mem, size contains no of bytes in a file WriteBinary.write(Buffer,headerSize);//writes header to 2nd image delete[] Buffer;//deallocate memory /* Buffer = new char[sizeof(long)]; Buffer = (char *)(&TextSourceSize); cout<<Buffer; */ WriteBinary.write((char *)(&TextSourceSize),sizeof(long)); //writes no of byte to be written in image immediate after header ends //to decrypt file if(!(Buffer=new char[TextSourceSize])) { cprintf("Enough Memory could not be assigned."); return 0; } ReadTxt.read(Buffer,TextSourceSize);//read all data from text file ReadTxt.close();//file no more needed WriteBinary.write(Buffer,TextSourceSize);//writes all text file data into image delete[] Buffer;//deallocate memory //replace Tsize+1 below with Tsize and run the program to see the change //this is due to the reason that 50-54 byte no are of colors which we will be changing ReadBinary.seekg(TextSourceSize+1,ios::cur);//move pointer to the location-current loc i.e. 53+content of text file //write remaining image content to image file while(i<BinarySourceSize-headerSize-TextSourceSize+1) { i=i+BlockSize; Buffer=new char[BlockSize]; ReadBinary.read(Buffer,BlockSize);//reads no of bytes and stores them into mem, size contains no of bytes in a file WriteBinary.write(Buffer,BlockSize); delete[] Buffer; //clear memory, else program can fail giving correct output } ReadBinary.close(); WriteBinary.close(); //Encoding Completed return 0; } Code to decrypt int Binary_decode(char *binarySourceFileName, char *txtTargetFileName, const short headerSize) { long TextDestinationSize=0; char *Buffer; long BlockSize=10240; ifstream ReadBinary; ofstream WriteText; ReadBinary.open(binarySourceFileName,ios::binary|ios::in);//file will be appended if(!ReadBinary) { cprintf("File can not be opened"); return 0; } ReadBinary.seekg(headerSize,ios::beg); Buffer=new char[4]; ReadBinary.read(Buffer,4); TextDestinationSize=*((long *)Buffer); delete[] Buffer; cout<<"\n\n"; cprintf("Size of the File that will be created is : "); cout<<TextDestinationSize; cprintf(" Bytes"); cout<<"\n\n"; sleep(1); WriteText.open(txtTargetFileName,ios::binary|ios::out|ios::trunc);//file will be created if not exists else truncate its data while(TextDestinationSize>0) { if(TextDestinationSize<BlockSize) BlockSize=TextDestinationSize; Buffer= new char[BlockSize]; ReadBinary.read(Buffer,BlockSize); WriteText.write(Buffer,BlockSize); delete[] Buffer; TextDestinationSize=TextDestinationSize-BlockSize; } ReadBinary.close(); WriteText.close(); return 0; } int text_encode(char *SourcefileName, char *DestinationfileName) { ifstream fr; //reads ofstream fw; // writes to file char c; int random; clrscr(); fr.open(SourcefileName,ios::binary);//file name, mode of open, here input mode i.e. read only if(!fr) { cprintf("File can not be opened."); getch(); return 0; } fw.open(DestinationfileName,ios::binary|ios::out|ios::trunc);//file will be created or truncated if already exists while(fr) { int i; while(fr!=0) { fr.get(c); //reads a character from file and increments its pointer char ch; ch=c; ch=ch+1; fw<<ch; //appends character in c to a file } } fr.close(); fw.close(); return 0; } int text_decode(char *SourcefileName, char *DestinationName) { ifstream fr; //reads ofstream fw; // wrrites to file char c; int random; clrscr(); fr.open(SourcefileName,ios::binary);//file name, mode of open, here input mode i.e. read only if(!fr) { cprintf("File can not be opened."); return 0; } fw.open(DestinationName,ios::binary|ios::out|ios::trunc);//file will be created or truncated if already exists while(fr) { int i; while(fr!=0) { fr.get(c); //reads a character from file and increments its pointer char ch; ch=c; ch=ch-1; fw<<ch; //appends character in c to a file } } fr.close(); fw.close(); return 0; }

    Read the article

  • How can I change the precision of printing with the stl?

    - by mmr
    This might be a repeat, but my google-fu failed to find it. I want to print numbers to a file using the stl with the number of decimal places, rather than overall precision. So, if I do this: int precision = 16; std::vector<double> thePoint(3); thePoint[0] = 86.3671436; thePoint[0] = -334.8866574; thePoint[0] = 24.2814; ofstream file1(tempFileName, ios::trunc); file1 << std::setprecision(precision) << thePoint[0] << "\\" << thePoint[1] << "\\" << thePoint[2] << "\\"; I'll get numbers like this: 86.36714359999999\-334.8866574\24.28140258789063 What I want is this: 86.37\-334.89\24.28 In other words, truncating at two decimal points. If I set precision to be 4, then I'll get 86.37\-334.9\24.28 ie, the second number is improperly truncated. I do not want to have to manipulate each number explicitly to get the truncation, especially because I seem to be getting the occasional 9 repeating or 0000000001 or something like that that's left behind. I'm sure there's something obvious, like using the printf(%.2f) or something like that, but I'm unsure how to mix that with the stl << and ofstream.

    Read the article

  • C++ reading and writing and writing files

    - by user320950
    Write a program that processes a list of items purchased with a receipt List in itemlist.txt just items different numbers Prices in pricelist.txt have items and prices in them, different # Make file output file that has receipt Print message saying program ran- have not done If item not in pricelist, report error, count errors display at end Don't know how many items or prices Close file and clear because of running many these files many times This program wont write to the files like so the above is what i have to do #include<iostream>`enter code here` #include<fstream> #include<cstdlib> #include<iomanip> using namespace std; int main() { ifstream in_stream; // reads itemlist.txt ofstream out_stream1; // writes in items.txt ifstream in_stream2; // reads pricelist.txt ofstream out_stream3;// writes in plist.txt ifstream in_stream4;// read recipt.txt ofstream out_stream5;// write display.txt double price=' ',curr_total=0.0; int wrong=0; int itemnum=' '; char next; in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items out_stream1.open("listWititems.txt", ios::out); // list of avaliable items in_stream2.open("PRICELIST.txt", ios::in); out_stream3.open("listWitdollars.txt", ios::out); in_stream4.open("display.txt", ios::in); out_stream5.open("showitems.txt", ios::out); in_stream.setf(ios::fixed); while(!in_stream.eof()) { in_stream >> itemnum; cin.clear(); cin >> next; } out_stream1.setf(ios::fixed); while (!out_stream1.eof()) { out_stream1 << itemnum; cin.clear(); cin >> next; } in_stream2.setf(ios::fixed); in_stream2.setf(ios::showpoint); in_stream2.precision(2); while (!in_stream2.eof()) // reads file to end of file { while((price== (price*1.00)) && (itemnum == (itemnum*1))) { in_stream2 >> itemnum >> price; itemnum++; price++; curr_total= price++; in_stream2 >> curr_total; cin.clear(); // allows more reading cin >> next; return itemnum, price; } } out_stream3.setf(ios::fixed); out_stream3.setf(ios::showpoint); out_stream3.precision(2); while (!out_stream3.eof()) // reads file to end of file { while((price== (price*1.00)) && (itemnum == (itemnum*1))) { out_stream3 << itemnum << price; itemnum++; price++; curr_total= price++; out_stream3 << curr_total; cin.clear(); // allows more reading cin >> next; return itemnum, price; } } in_stream4.setf(ios::fixed); in_stream4.setf(ios::showpoint); in_stream4.precision(2); while (!in_stream4.eof()) { in_stream4 >> itemnum >> price >> curr_total; cin.clear(); cin >> next; } out_stream5.setf(ios::fixed); out_stream5.setf(ios::showpoint); out_stream5.precision(2); out_stream5 <<setw(5)<< " itemnum " <<setw(5)<<" price "<<setw(5)<<" curr_total " <<endl; // sends items and prices to receipt.txt out_stream5 << setw(5) << itemnum << setw(5) <<price << setw(5)<< curr_total; // sends items and prices to receipt.txt out_stream5 << " You have a total of " << wrong++ << " errors " << endl; in_stream.close(); // closing files. out_stream1.close(); in_stream2.close(); out_stream3.close(); in_stream4.close(); out_stream5.close(); system("pause"); }

    Read the article

  • Programs won't write to a file, and I do not know if it is reading it

    - by user320950
    This program is supposed to read files and write them. I took the file open checks out because they kept causing errors. The problem is that the files open like they are supposed to and the names are correct but nothing is on any of the text screens. Do you know what is wrong? #include<iostream> #include<fstream> #include<cstdlib> #include<iomanip> using namespace std; int main() { ifstream in_stream; // reads itemlist.txt ofstream out_stream1; // writes in items.txt ifstream in_stream2; // reads pricelist.txt ofstream out_stream3;// writes in plist.txt ifstream in_stream4;// read recipt.txt ofstream out_stream5;// write display.txt float price=' ',curr_total=0.0; int itemnum=' ', wrong=0; char next; in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items out_stream1.open("listWititems.txt", ios::out); // list of avaliable items in_stream2.open("PRICELIST.txt", ios::in); out_stream3.open("listWitdollars.txt", ios::out); in_stream4.open("display.txt", ios::in); out_stream5.open("showitems.txt", ios::out); in_stream.close(); // closing files. out_stream1.close(); in_stream2.close(); out_stream3.close(); in_stream4.close(); out_stream5.close(); system("pause"); in_stream.setf(ios::fixed); while(in_stream.eof()) { in_stream >> itemnum; cin.clear(); cin >> next; } out_stream1.setf(ios::fixed); while (out_stream1.eof()) { out_stream1 << itemnum; cin.clear(); cin >> next; } in_stream2.setf(ios::fixed); in_stream2.setf(ios::showpoint); in_stream2.precision(2); while((price== (price*1.00)) && (itemnum == (itemnum*1))) { while (in_stream2 >> itemnum >> price) // gets itemnum and price { while (in_stream2.eof()) // reads file to end of file { in_stream2 >> itemnum; in_stream2 >> price; price++; curr_total= price++; in_stream2 >> curr_total; cin.clear(); // allows more reading cin >> next; } } } out_stream3.setf(ios::fixed); out_stream3.setf(ios::showpoint); out_stream3.precision(2); while((price== (price*1.00)) && (itemnum == (itemnum*1))) { while (out_stream3 << itemnum << price) { while (out_stream3.eof()) // reads file to end of file { out_stream3 << itemnum; out_stream3 << price; price++; curr_total= price++; out_stream3 << curr_total; cin.clear(); // allows more reading cin >> next; } return itemnum, price; } } in_stream4.setf(ios::fixed); in_stream4.setf(ios::showpoint); in_stream4.precision(2); while ( in_stream4.eof()) { in_stream4 >> itemnum >> price >> curr_total; cin.clear(); cin >> next; } out_stream5.setf(ios::fixed); out_stream5.setf(ios::showpoint); out_stream5.precision(2); out_stream5 <<setw(5)<< " itemnum " <<setw(5)<<" price "<<setw(5)<<" curr_total " <<endl; // sends items and prices to receipt.txt out_stream5 << setw(5) << itemnum << setw(5) <<price << setw(5)<< curr_total; // sends items and prices to receipt.txt out_stream5 << " You have a total of " << wrong++ << " errors " << endl; }

    Read the article

  • three out of five file streams wont open, i believe its a problem with my ifstreams.

    - by user320950
    #include<iostream> #include<fstream> #include<cstdlib> #include<iomanip> using namespace std; int main() { ifstream in_stream; // reads itemlist.txt ofstream out_stream1; // writes in items.txt ifstream in_stream2; // reads pricelist.txt ofstream out_stream3;// writes in plist.txt ifstream in_stream4;// read recipt.txt ofstream out_stream5;// write display.txt int wrong=0; in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items if( in_stream.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; out_stream1.open("ITEMLIST.txt", ios::out); // list of avaliable items if(out_stream1.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here1, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit(1); } else{ cout << " System ran correctly " << endl; } in_stream2.open("PRICELIST.txt", ios::in); if( in_stream2.fail() ) { wrong++; cout << " the error occured here2, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; } out_stream3.open("PRICELIST.txt", ios::out); if(out_stream3.fail() ) { wrong++; cout << " the error occured here3, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; } in_stream4.open("display.txt", ios::in); if( in_stream4.fail() ) { wrong++; cout << " the error occured here4, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; } out_stream5.open("display.txt", ios::out); if( out_stream5.fail() ) { wrong++; cout << " the error occured here5, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; }

    Read the article

1 2 3 4 5  | Next Page >