I have two text files "source1" and "source2" that contain integers 3 4 1 2 56 and 2 45 34 23 45 respectively.
Displaying them on the screen.
Even though there is not any error given but what i am sure is that those array isn't getting the correct data from the files source1 and source2.
The ouput should be the integers in the file but it's not what i expected.
i guess there is some problem with my READ and WRITE.
#include<stdio.h>
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
fstream file1;
fstream file2;
file1.open("source1.txt");
file2.open("source2.txt");
int source1[20];
int source2[20];
file1.read((char*)&source1,sizeof(source1));
cout<<source1<<"\n";
file2.read((char*)&source2,sizeof(source2));
cout<<source2<<"\n";
}
Here are some issues I noticed with your program.
Reading Arrays
Your code reads in 20 integers, whether there are 20 or not. If the file contains 4 binary integers, how do you handle the error?
Your file ends with a .txt extension, so I assume the data is in human readable (text) format. The read method does not translate "123" into the number 123. The read method will save a mirror of the data, as is.
Arrays and cout
The C++ programming language's cout does not have facilities for printing arrays of integers. You'll have to use a loop to print them. Also, you should use a separator between the integers, such as tab, newline, comma or space.
Binary & Text writing
If you want to write the internal representation of a number, use ostream::write. If you want to use formatted or textual representation use operator>>.
If the integer is more than a byte wide you will need to know if the platform outputs the highest byte first (Big Endian) or last (Little Endian). This makes a big difference when you read the values back.
Use Vectors not Arrays
Vectors are easier to pass and they take care of dynamic growth. Arrays are fixed capacity by definition and require 3 parameters when passing: The array, the capacity, and the quantity of items in the array. With std::vector, only the vector needs to be passed because all the other information can be obtained by calling vector methods, such as vector::size().
When opening files in C or C++ to write binary data, you have to open them in binary mode. Use:
file1.open("source1.txt", ios::in | ios::binary);
file2.open("source2.txt", ios::out | ios::binary);
Or similar flags.
Here is working code that describes what you are trying to achieve:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
bool readIntsFromFile( const std::string& strFilename, std::vector<int>& v ) {
std::fstream inFile;
inFile.open( strFilename.c_str(), std::ios_base::in );
if ( !inFile.is_open() ) {
return false;
} else {
int val;
while ( !inFile.eof() ) {
inFile >> val;
v.push_back( val );
}
}
inFile.close();
return true;
}
void sortVectors( const std::vector<int>& v1, const std::vector<int>& v2, std::vector<int>& out ) {
unsigned index = 0;
for ( ; index < v1.size(); ++index ) {
out.push_back( v1[index] );
}
index = 0;
for ( ; index < v2.size(); ++index ) {
out.push_back( v2[index] );
}
std::sort( out.begin(), out.end() );
}
int main() {
const std::string strFile1( "source1.txt" );
const std::string strFile2( "source2.txt" );
const std::string strOutput( "output.txt" );
std::vector<int> a;
std::vector<int> b;
std::vector<int> res;
if ( !readIntsFromFile( strFile1, a ) ) {
return -1;
}
if ( !readIntsFromFile( strFile2, b ) ) {
return -1;
}
sortVectors( a, b, res );
unsigned index = 0;
for ( ; index < res.size(); ++index ) {
std::cout << res[index] << " ";
}
std::cout << std::endl;
std::fstream out;
out.open( strOutput.c_str(), std::ios_base::out );
if ( !out.is_open() ) {
return -1;
} else {
index = 0;
for ( ; index < res.size(); ++index ) {
out << res[index] << " ";
}
}
out.close();
return 0;
}
Just make sure that your source1 & source2 text files are in the same directory
as your generated executable.
Related
So i have a struct called info that contains different kind of variable and i created a vector inside of this struct. now i want to save this vector into a binary file so i can read it later.
My code so far
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
struct MyStruct
{
int a;
};
struct info
{
char name[30];
int age;
char bbl[20];
std::vector<MyStruct> my;
};
void create(std::vector<info>& test)
{
std::ofstream file("info.dat", std::ios::binary | std::ios::app); // output file stream
// dump the contents of the vector in the file
for (const info& inf : test)
file.write(reinterpret_cast<const char*>(&inf), sizeof(inf));
}
int main()
{
info info1;
// create a test vector
std::vector<info> test;
info1.age = 3443;
std::cin >> info1.name;
std::cin >> info1.bbl;
MyStruct my;
my.a = 4;
info1.my.push_back(my);
test.push_back(info1);
std::cout << '\n';
create(test);
test.clear(); // clear the vector
{
std::ifstream file("info.dat", std::ios::binary); // input file stream
// read the contents of the file into the vector
info inf;
while (file.read(reinterpret_cast<char*>(&inf), sizeof(inf)))
test.push_back(inf);
}
// print out the contents of test
for (int i = 0; i < test.size(); i++)
std::cout << "{ " << test[i].name << ", " << test[i].age << ", " << test[i].bbl << " } ";
std::cout << '\n';
}
But i got error on while (file.read(reinterpret_cast<char*>(&inf), sizeof(inf))) which is
Exception thrown at 0x7AD63E9E (vcruntime140d.dll) in
ConsoleApplication9.exe: 0xC0000005: Access violation reading location
0xCC007364.
How can i fix that?
The std::vector object itself probably does not contain any actual data. Instead, it probably only contains bookkeeping information, for example
the number of valid elements,
the maximum number of elements for which memory has been allocated, and
a pointer to the start of the actual data.
Therefore, simply dumping the contents of the std::vector object to file will not be useful.
If you want to write the actual data of a std::vector to file, you must first decide how it should be stored in the file. One simple way of storing it would be to first write the number of elements as an int to the file, and then to write all of the individual elements to the file one after another. That way, when reading the file later, the reading function can easily find out how many elements it should read from the file, simply by reading the first value.
You may want to change your function create to the following:
void create(std::vector<info>& test)
{
std::ofstream file("info.dat", std::ios::binary );
for ( const info& inf : test )
{
//write "name" member to file
file.write( reinterpret_cast<const char*>(&inf.name), sizeof inf.name );
//write "age" member to file
file.write( reinterpret_cast<const char*>(&inf.age), sizeof inf.age );
//write "bbl" member to file
file.write( reinterpret_cast<const char*>(&inf.bbl), sizeof inf.bbl );
//write "my" member to file, giving it special treatment,
//because it is a std::vector
{
int num_elements = inf.my.size();
//write number of elements to file
file.write( reinterpret_cast<const char*>(&num_elements), sizeof num_elements );
//write the individual elements to file
for ( int i = 0; i < num_elements; i++ )
{
file.write( reinterpret_cast<const char*>(&inf.my[i]), sizeof inf.my[i] );
}
}
}
//verify that stream is still in a good state
if ( !file )
throw std::runtime_error( "output error" );
}
Note that I removed std::ios::app in the code above, because it did not seem appropriate for what you are doing.
For reading the file contents, you can now use the following function:
void read(std::vector<info>& test)
{
std::ifstream file("info.dat", std::ios::binary );
info inf;
//try reading new entries from file until end-of-file or error occurs
for (;;)
{
//read "name" member from file
file.read( reinterpret_cast<char*>(&inf.name), sizeof inf.name );
//read "age" member from file
file.read( reinterpret_cast<char*>(&inf.age), sizeof inf.age );
//read "bbl" member from file
file.read( reinterpret_cast<char*>(&inf.bbl), sizeof inf.bbl );
//read "my" member from file, giving it special treatment,
//because it is a std::vector
{
int num_elements;
//read number of elements from file
file.read( reinterpret_cast<char*>(&num_elements), sizeof num_elements );
//don't start loop if loop counter is invalid
if ( !file )
break;
//read the individual elements from file
for ( int i = 0; i < num_elements; i++ )
{
MyStruct my;
file.read( reinterpret_cast<char*>(&my), sizeof my );
if ( file )
inf.my.push_back( my );
else
break;
}
//stop main loop if data was not successfully read
if ( !file )
break;
test.push_back( inf );
}
}
}
Your entire program will now look like this:
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
struct MyStruct
{
int a;
};
struct info
{
char name[30];
int age;
char bbl[20];
std::vector<MyStruct> my;
};
void create(std::vector<info>& test)
{
std::ofstream file("info.dat", std::ios::binary );
for ( const info& inf : test )
{
//write "name" member to file
file.write( reinterpret_cast<const char*>(&inf.name), sizeof inf.name );
//write "age" member to file
file.write( reinterpret_cast<const char*>(&inf.age), sizeof inf.age );
//write "bbl" member to file
file.write( reinterpret_cast<const char*>(&inf.bbl), sizeof inf.bbl );
//write "my" member to file, giving it special treatment,
//because it is a std::vector
{
int num_elements = inf.my.size();
//write number of elements to file
file.write( reinterpret_cast<const char*>(&num_elements), sizeof num_elements );
//write the individual elements to file
for ( int i = 0; i < num_elements; i++ )
{
file.write( reinterpret_cast<const char*>(&inf.my[i]), sizeof inf.my[i] );
}
}
}
//verify that stream is still in a good state
if ( !file )
throw std::runtime_error( "output error" );
}
void read(std::vector<info>& test)
{
std::ifstream file("info.dat", std::ios::binary );
info inf;
//try reading new entries from file until end-of-file or error occurs
for (;;)
{
//read "name" member from file
file.read( reinterpret_cast<char*>(&inf.name), sizeof inf.name );
//read "age" member from file
file.read( reinterpret_cast<char*>(&inf.age), sizeof inf.age );
//read "bbl" member from file
file.read( reinterpret_cast<char*>(&inf.bbl), sizeof inf.bbl );
//read "my" member from file, giving it special treatment,
//because it is a std::vector
{
int num_elements;
//read number of elements from file
file.read( reinterpret_cast<char*>(&num_elements), sizeof num_elements );
//don't start loop if loop counter is invalid
if ( !file )
break;
//read the individual elements from file
for ( int i = 0; i < num_elements; i++ )
{
MyStruct my;
file.read( reinterpret_cast<char*>(&my), sizeof my );
if ( file )
inf.my.push_back( my );
else
break;
}
//stop main loop if data was not successfully read
if ( !file )
break;
test.push_back( inf );
}
}
}
int main()
{
info info1;
// create a test vector
std::vector<info> test;
info1.age = 3443;
std::cin >> info1.name;
std::cin >> info1.bbl;
MyStruct my;
my.a = 4;
info1.my.push_back(my);
test.push_back(info1);
std::cout << '\n';
create(test);
test.clear(); // clear the vector
read( test );
// print out the contents of test
for (int i = 0; i < test.size(); i++)
std::cout << "{ " << test[i].name << ", " << test[i].age << ", " << test[i].bbl << " } ";
std::cout << '\n';
}
This program has the following output:
TestName
TestBBL
{ TestName, 3443, TestBBL }
As you can see, the written data was read back properly.
You can read/write vector in binary, or vector of structure, as long as the struct is POD. The whole data can be obtained from vec.data() and the size of data is vec.size() * sizeof(vec[0])
In your example, the structure is not POD, this method can't be used. But the structure can be broken down in to POD + sub vector, and we can read/write each individual element.
Note however that this method is OS dependent. The binary data can be stored in big-endian or little-endian format, the structure size may vary between compilers. The file is not portable, at least not without additional work.
(This code requires C++ 17)
#include <iostream>
#include <fstream>
#include <vector>
struct info_pod
{ char name[30]; int age; char bbl[20]; };
struct info : info_pod
{ std::vector<int> subvec; };
int main()
{
std::vector<info> src{
{ "name1", 100, "bbl1", { {10}, {11}, {12} } },
{ "name2", 101, "bbl2", { {10}, {11}, {12} } },
{ "name3", 102, "bbl3", { {10}, {11}, {12} } }
};
std::ofstream fout("info.dat", std::ios::binary);
if (!fout)
return 0;
for (auto& e : src)
{
fout.write((char*)&e, sizeof(info_pod));
size_t count = e.subvec.size();
fout.write((char*)&count, sizeof(count));
auto vecsize = count * sizeof(e.subvec[0]);
fout.write((char*)e.subvec.data(), vecsize);
}
fout.close();
//read it back
std::ifstream fin("info.dat", std::ios::binary);
if (!fin)
return 0;
std::vector<info> dst;
while (true)
{
info inf;
fin.read((char*)&inf, sizeof(info_pod));
if (fin.gcount() != sizeof(info_pod)) break;
size_t count;
fin.read((char*)&count, sizeof(count));
if (fin.gcount() != sizeof(count)) break;
inf.subvec.resize(count);
auto vecsize = count * sizeof(inf.subvec[0]);
fin.read((char*)inf.subvec.data(), vecsize);
if (fin.gcount() != vecsize) break;
dst.push_back(inf);
}
for (auto& e : dst)
{
std::cout << e.name << ',' << e.age << ',' << e.bbl << " MyStruct: ";
for (auto& i : e.subvec) std::cout << i << ',';
std::cout << '\n';
}
}
I have a file with 9 words and i have to store each word into the char array of 9 pointers but i keep getting an error message. I cannot use vectors!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char *words[9];
ifstream inStream;
inStream.open("sentence.txt");
if (inStream.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
for ( int i = 0; i < 10; i++)
{
inStream >> words[i];
}
inStream.close();
return 0;
}
The declaration
char *words[9];
declares a raw array of pointers. This array is not initialized so the pointers have indeterminate values. Using any of them would be Undefined Behavior.
Instead you want
vector<string> words;
where vector is std::vector from the <vector> header, and string is std::string from the <string> header.
Use the push_back member function to add strings to the end of the vector.
Also you need to move the close call out of the loop. Otherwise it will close the file in the first iteration.
This approach gives the code (off the cuff, disclaimer...)
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> words;
ifstream inStream;
inStream.open("sentence.txt");
for ( int i = 0; i < 10; i++)
{
string word;
if( inStream >> word )
words.push_back( word );
}
inStream.close();
}
If you can't use std::string and std::vector then you need to initialize the array of pointers, and make sure that you don't read more into the buffers than there's room for.
The main problem here is that >> is unsafe for reading into a raw array given by a pointer. It doesn't know how large that array is. It can easily lead to a buffer overrun, with dire consequences.
And so this gets a bit complicated, but it can look like this:
#include <ctype.h> // isspace
#include <fstream>
#include <iostream>
#include <locale.h> // setlocale, LC_ALL
#include <stdlib.h> // EXIT_FAILURE
using namespace std;
void fail( char const* const message )
{
cerr << "! " << message << "\n";
exit( EXIT_FAILURE );
}
void readWordFrom( istream& stream, char* const p_buffer, int const buffer_size )
{
int charCode;
// Skip whitespace:
while( (charCode = stream.get()) != EOF and isspace( charCode ) ) {}
int n_read = 0;
char* p = p_buffer;
while( n_read < buffer_size - 1 and charCode != EOF and not isspace( charCode ) )
{
*p = charCode; ++p;
++n_read;
charCode = stream.get();
}
*p = '\0'; // Terminating null-byte.
if( charCode != EOF )
{
stream.putback( charCode );
if( not isspace( charCode ) )
{
assert( n_read == buffer_size - 1 ); // We exceeded buffer size.
stream.setstate( ios::failbit );
}
}
}
int main()
{
static int const n_words = 9;
static int const max_word_length = 80;
static int const buffer_size = max_word_length + 1; // For end byte.
char *words[n_words];
for( auto& p_word : words ) { p_word = new char[buffer_size]; }
ifstream inStream{ "sentence.txt" };
if( inStream.fail() ) { fail( "Input file opening failed." ); }
setlocale( LC_ALL, "" ); // Pedantically necessary for `isspace`.
for( auto const p_word : words )
{
readWordFrom( inStream, p_word, buffer_size );
if( inStream.fail() ) { fail( "Reading a word failed." ); }
}
for( auto const p_word : words ) { cout << p_word << "\n"; }
for( auto const p_word : words ) { delete[] p_word; }
}
You never allocate any memory for your char* pointers kept in the array.
The idiomatic way to write a c++ code would be:
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::vector<std::string> words(9);
std::ifstream inStream;
inStream.open("sentence.txt");
for ( int i = 0; inStream && i < 9; i++) {
inStream >> words[i];
}
}
The inStream.close() isn't necessary, and even wrong inside the loop. The std::istream will be closed automatically as soon the variable goes out of scope.
There are a few problems with your code.
char *words[9];
This allocates space for 9 pointers, not nine strings. Since you don't know how big the strings are you have two choices. You can either "guess" how much you'll need and limit the inputs accordingly, or you can use dynamic memory allocation (malloc or new) to create the space you need to store the strings. Dynamic memory would be my choice.
for ( int i = 0; i < 10; i++)
This loop will execute on words[0] through words[9]. However, there is no words[9] (that would be the tenth word) so you'll overwrite memory that you have not allocated
inStream >> words[i];
This will send your input stream to memory that you don't "own". You need to allocate space for the words to live before capturing them from the input stream. To do this correctly, you'll need to know how much space each word will need so you can allocate it.
you could try something like this:
int main()
{
char *words[9];
char tempInput[256]; // space to capture the input, up to a maximum size of 256 chars
ifstream inStream;
inStream.open("sentence.txt");
if (inStream.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
for ( int i = 0; i < 9; i++)
{
//Clear the input buffer
memset(tempInput, 0, 256);
//Capture the next word
inStream >> tempInput;
//allocate space to save the word
words[i] = new char(strlen(tempInput));
//Copy the word to its final location
strcpy(words[i], tempInput)
}
inStream.close();
return 0;
}
I got a problem using strings. So I had the idea of writing a program, that multiplicates two parenthesis, since I had some with 10 variables each. I put a parenthesis in a .txt file and wanted to read it and just print into another .txt file. I am not sure if it has problems with the specific signs.
So here is my txt that I read
2*x_P*x_N - x_P^2 + d_P - 2*x_N*x_Q + x_Q^2 - d_Q
and here is what it actually prints
2*x_--x_P^++d_P-2*x_++x_Q^--
as You can see it is completely wrong. In addition I get an error after executing, but it still prints it into the .txt. So here is my code:
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int i;
const int size = 11;
string array[ size ];
FILE * file_read;
file_read = fopen( "alt.txt", "r" );
for( i = 0; i < size; i++ ) //Read
{
fscanf( file_read, "%s", &array[ i ] );
}
fclose( file_read );
FILE * file_write;
file_write = fopen( "neu.txt", "w" );
for( i = 0; i < size; i++ ) //Write
{
fprintf( file_write, "%s", &array[ i ] );
}
fclose( file_write ); printf("test");
return 1;
}
Thanks for suggestions. You can put suggestions made with iostream as well.
You are mixing C++ and C forms of file input:
When you write:
fscanf( file_read, "%s", &array[ i ] );
the C standard library expects that you provide a pointer to a buffer in which the string read in the file will be stored in form of a C string, that is an array of null terminated characters.
Unfortunately, you provide a pointer to a C++ string. So this will result in undefined behaviour (most probably memory corruption).
Solution 1
If you want to keep using the C standard library file i/o, you have to use an interim buffer:
char mystring[1024]; //for storing the C string
...
fscanf( file_read, "%1023s", mystring );
array[ i ] = string(mystring); // now make it a C++ string
Please note that the format is slightly changed, in order to avoid risks of buffer overflow in case the file contains a string that is larger than your buffer.
Solution 2
If you learn C++ (looking at your C++ tag and the string header), I'd strongly suggest that you have a look at fstream in the C++ library. It's designed to work very well with strings.
Here how it could look like:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
const int size = 11;
string array[ size ];
ifstream file_read( "alt.txt");
for(int i = 0; i < size && file_read >> array[ i ]; i++ ) //Read
;
file_read.close();
ofstream file_write("neu.txt");
for(int i = 0; i < size; i++ ) //Write
file_write << array[ i ] <<" "; // with space separator
file_write.close();
cout << "test"<<endl;
return 0;
}
And of course, the next thing you should consider, would be to replace classic arrays with vectors (you don't have to define their size in advance).
I am reading numbers from a file, say:
1 2 3 4 5
I want to read this data from a file into a string into an array for further processing. Here's what I've done:
float *ar = nullptr;
while (getline(inFile, line))
{
ar = new float[line.length()];
for (unsigned int i = 0; i < line.length(); i++)
{
stringstream ss(line);
ss >> ar[i];
}
}
unsigned int arsize = sizeof(ar) / sizeof(ar[0]);
delete ar;
Suffice it to say that it works insofar it only gets the first value from the file. How do I get the array to be input ALL the values? I debugged the program and I can confirm that line has all the necessary values; but the float array doesn't. Please help, thanks!
line.length() is the number of characters in the line, not the number of words/numbers/whatevers.
Use a vector, which can be easily resized, rather than trying to juggle pointers.
std::vector<float> ar;
std::stringstream ss(line);
float value;
while (ss >> value) { // or (inFile >> value) if you don't care about lines
ar.push_back(value);
}
The size is now available as ar.size(); your use of sizeof wouldn't work since ar is a pointer, not an array.
The easiest option is to use the standard library and its streams.
$ cat test.data
1.2 2.4 3 4 5
Given the file you can use the stream library like this:
#include <fstream>
#include <vector>
#include <iostream>
int main(int argc, char *argv[]) {
std::ifstream file("./test.data", std::ios::in);
std::vector<float> res(std::istream_iterator<float>(file),
(std::istream_iterator<float>()));
// and print it to the standard out
std::copy(std::begin(res), std::end(res),
std::ostream_iterator<float>(std::cout, "\n"));
return 0;
}
I ran into this problem earlier when I wanted to extract data line by line from a file to fill my sql database that I wanted to use.
There are many solutions to this specific problem such as:
The solution is using stringstream with a while statement to put data from file into the array with a while statement
//EDIT
While statement with getline
//This solution isn't very complex and is pretty easy to use.
New Improved simple solution:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream line;
line.open("__FILENAME__");
string s;
vector<string> lines;
while(getline(line, s))
{
lines.push_back(s);
}
for(int i = 0;i < lines.size();i++)
{
cout << lines[i] << " ";
}
return 0;
}
compiled code to check - http://ideone.com/kBX45a
What about atof?
std::string value = "1.5";
auto converted = atof ( value.c_str() );
Rather complete:
while ( std::getline ( string ) )
{
std::vector < std::string > splitted;
boost::split ( splitted, line, boost::is_any_of ( " " ) );
std::vector < double > values;
for ( auto const& str: splitted ) {
auto value = atof ( str.c_str() );
values.push_back ( value );
}
}
I would like to know how to output an array of doubles to the hard drive.
edit:
for further clarification. I would like to output it to a file on the hard drive (I/O functions). Preferably in a file format that can be quickly translated back into an array of doubles in another program. It would also be nice if it was stored in a standard 4 byte configuration so that i can look at it through a hex viewer and see the actual values.
Hey... so you want to do it in a single write/read, well its not too hard, the following code should work fine, maybe need some extra error checking but the trial case was successful:
#include <string>
#include <fstream>
#include <iostream>
bool saveArray( const double* pdata, size_t length, const std::string& file_path )
{
std::ofstream os(file_path.c_str(), std::ios::binary | std::ios::out);
if ( !os.is_open() )
return false;
os.write(reinterpret_cast<const char*>(pdata), std::streamsize(length*sizeof(double)));
os.close();
return true;
}
bool loadArray( double* pdata, size_t length, const std::string& file_path)
{
std::ifstream is(file_path.c_str(), std::ios::binary | std::ios::in);
if ( !is.is_open() )
return false;
is.read(reinterpret_cast<char*>(pdata), std::streamsize(length*sizeof(double)));
is.close();
return true;
}
int main()
{
double* pDbl = new double[1000];
int i;
for (i=0 ; i<1000 ; i++)
pDbl[i] = double(rand());
saveArray(pDbl,1000,"test.txt");
double* pDblFromFile = new double[1000];
loadArray(pDblFromFile, 1000, "test.txt");
for (i=0 ; i<1000 ; i++)
{
if ( pDbl[i] != pDblFromFile[i] )
{
std::cout << "error, loaded data not the same!\n";
break;
}
}
if ( i==1000 )
std::cout << "success!\n";
delete [] pDbl;
delete [] pDblFromFile;
return 0;
}
Just make sure you allocate appropriate buffers! But thats a whole nother topic.
Use std::copy() with the stream iterators. This way if you change 'data' into another type the alterations to code would be trivial.
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
double data[1000] = {/*Init Array */};
{
// Write data too a file.
std::ofstream outfile("data");
std::copy(data,
data+1000,
std::ostream_iterator<double>(outfile," ")
);
}
{
// Read data from a file
std::ifstream infile("data");
std::copy(std::istream_iterator<double>(infile),
std::istream_iterator<double>(),
data // Assuming data is large enough.
);
}
}
You can use iostream .read() and .write().
It works (very roughly!) like this:
double d[2048];
fill(d, d+2048, 0);
ofstream outfile ("save.bin", ios::binary);
outfile.write(reinterpret_cast<char*>(&d), sizeof(d));
ifstream infile ("save.bin", ios::binary);
infile.read(reinterpret_cast<char*>(&d), sizeof(d));
Note that this is not portable between CPU architectures. Some may have different sizes of double. Some may store the bytes in a different order. It shouldn't be used for data files that move between machines or data that is sent over the network.
#include <fstream.h>
void saveArray(double* array, int length);
int main()
{
double array[] = { 15.25, 15.2516, 84.168, 84356};
saveArray(array, 4);
return 0;
}
void saveArray(double* array, int length)
{
ofstream output("output.txt");
for(int i=0;i<length;i++)
{
output<<array[i]<<endl;
}
}
here is a way to output an array of doubles to text file one per line. hope this helps
EDIT
Change top one line to this two, and it will compile in VS. You can use multithreading to not blocking system wile saving data
#include <fstream>
using namespace std;
Now I feel old. I asked this question a long time ago (except about ints).
comp.lang.c++ link
#include <iostream>
#include <fstream>
using namespace std;
int main () {
double [] theArray=...;
int arrayLength=...;
ofstream myfile;
myfile.open ("example.txt");
for(int i=0; i<arrayLength; i++) {
myfile << theArray[i]<<"\n";
}
myfile.close();
return 0;
}
adapted from http://www.cplusplus.com/doc/tutorial/files/
Just set theArray and arrayLength to whatever your code requires.