Having Open File Function Trouble - c++

I'm new to c++ coding. I'm trying to write a function that opens specified ".txt" files(I fed up with coping/pasting multiple times).What I need to realize:
Specify filename;
read data and save to double(type) array;
return array;
As far as I understood, c++ can't return array, but it can return pointer. The problem is: how to use it? Any help will be appreciated. :)
P.S My draft code (it's working):
double arr[10];
fstream file;
file.open("input.txt");
if(file.is_open()){
while(file.good()){
for(int i = 0 ; i < 10 ; i++){
file >> arr[i];
}
}
file.close();
}else{
cout<<"[ERROR]: File \"input.txt\" wasn't found!"<<endl;
cout<<"[INFO]: Terminating program...";
Sleep(1000);
exit(0);
}

I dunno how to write as a function. Moreover I dunno how to use it
To start, try this:
std::vector<double> theFunction(const std::string &filename)
{
std::vector<double> arr(10);
std::fstream file(filename);
if (file)
{
for (int i = 0 ; i < 10 && file.good(); i++)
file >> arr[i];
}
return arr;
}
std::vector<double> result = theFunction("input.txt");
if (result.empty())
// Can not read the file

Related

c++ i get duplicated info when i read a binary file

Im writing a vector of size three and when i read i get a vector of size 4 with the last index being a duplicate of the index 2.
Heres my code.
void IOManager::WriteBin(const string &filename, vector<userRank> highScorers, int rank) {
ofstream fsalida(filename, ios::out | ios::binary);
if (fsalida.is_open())
{
for (int i = 0; i < highScorers.size();i++) {
fsalida.write(reinterpret_cast<char*>(&highScorers[i]), sizeof(highScorers[i]));
}
//highScorers.size() is 3
fsalida.close();
}else cout << "Unable to open file for writing\n";
}
vector<userRank> IOManager::ReadBin(const string &filename) {
ifstream fentrada(filename, ios::in | ios::binary);
if (fentrada.is_open())
{
vector<userRank>bestPlayers;
for (int i = 0; fentrada.good(); i++) {
userRank tempUser;
fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
bestPlayers.push_back(tempUser);
}
//bestPlayers.size() is 4!!!!!! Im losing my mind
fentrada.close();
return bestPlayers;
}
else cout << "Unable to open file for reading\n";
}
Here's my UserRank struct
struct userRank
{
char userName [5];
int score;
};
A wild userRank apperars for some reason, does anybody know why?
I suggest reorganizing the read function:
userRank tempUser;
for (int i = 0;
fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
i++)
{
bestPlayers.push_back(tempUser);
}
Search the internet for "stackoverflow c++ why eof in while is bad".

guessing datatype of data in .txt file

I have file with some data. I would like to decide what type of data there are: if everythng there is a number I want to push that to vector. But if there is even one data that is now a string I would like to push all of it to vector. I wrote something like this:
ifstream dataFile;
dataFile.open(fileName);
if(!dataFile.good()){
cout<<"File with data cannot be open"<<endl;
return 0;
}
cout<<"File open correctly..."<<endl;
bool isString = false;
vector<double> doubleData;
while (!dataFile.eof()){
double f;
dataFile>>f;
if(!dataFile.fail()){
doubleData.push_back(f);
}
else{
cout<<"it's string"<<endl; //(*) always
isString = true;
break;
}
}
if(isString){
dataFile.close(); //(**) reopen a file
dataFile.open(fileName);
vector<string> stringData;
while (!dataFile.eof()){
string s;
dataFile>>s;
if(!dataFile.fail()){
stringData.push_back(s);
}
}
cout<<"String data:"<<endl;
for (int i = 0; i< stringData.size();i++){
cout<<stringData[i]<<endl;
}
//showTime(stringData);
return 0;
}
cout<<"double data:"<<endl;
for (int i = 0; i< doubleData.size();i++){
cout<<doubleData[i]<<endl;
}
//showTime(doubleData);
return 0;
My code always reach line (*) at the end and therefore presume it's string data. I think it's when it reaches eof(). Am I right? How to fix it?
And one more: I need to re-open my file (*line (**)*) to read data into stringData properly. I can guess it is because I am at the end of file after previous while loop. Am I right? Is there any other, more elegant way to do this? Moving cursor in file to the beginning? I know there is something like fseek ( dataFile , 0 , SEEK_SET ); but I receive compiler error as my dataFile is ifstream instead of File*. Any suggestions?

Read file in as 32 bit binary data c++

I need to read a file in as binary data, making sure the file is an even number of 32 bit words (I can add padding bytes of 0s if I need).
I've fiddled around with ios::binary but is there something I'm missing? For instance:
string name1 = "first", name2 = "sec", name3 = "third";
int j = 0, k = 0;
ifstream ifs(name1.c_str());
ifs >> j;
ifs.close();
Is this something I need to utilize? I'm fairly new to the language.
std::ifstream ifs(name1.c_str(), std::ifstream::binary);
if (!ifs)
{
// error opening file
}
else
{
int32_t j;
do
{
j = 0;
ifs.read(&j, sizeof(j));
if (ifs)
{
// read OK, use j as needed
}
else
{
if (ifs.eof())
{
// EOF reached, use j padded as needed
}
else
{
// error reading from file
}
break;
}
}
while (true);
ifs.close();
}
I was able to read 32bits using a similar method as Remy Lebeau. This code is compatible with C++03.
#include <stdint.h>
#include <fstream>
// Rest of code...
std::ifstream file(fileName, std::ifstream::in | std::ifstream::binary | std::ifstream::beg);
int32_t word;
if(!file){
//error
} else {
while(file.is_open()){
if(file.eof()){ printf("END\n"); break; }
word = 0;
file.read((char*)&word,sizeof(word));
//Do something
printf("%d\n",word);
}
}
Note that I do not add padding if the file is not in exact increments of 32. I'll update the code if I add that functionality.

ifstream wont read all integer

When i read TestData.txt file it gives me wrong output. What am i doing wrong. I am using int array so i can do MergeSort after saving data into array.
TestData.txt
-------------------
31791 564974 477059 269094 972335
739154 206345 634644 227684 398536
910177 507975 589785 67117 395140
598829 372499 364165 450187 996527
700285 263407 918021 661467 457544
656297 846316 221731 240676 68287
913 141702 845802 477617 109824
{
int myArray[1000];
int i;
//reading givin data
const char* filename= "TestData.txt";
ifstream file(filename);
if(file.is_open())
{
for(i = 0; i <=999; ++i)
{
file >> myArray[i];//storing data to array
}
}
Need to check if you ifstream is end of file, in that case you get garbage value from out of the file bound.
With One modification, the code would be OK.
Change:
for(i = 0; i <=999; ++i)
to:
for(i = 0; i <=999 && !file.eof(); ++i)
You are reading 1000 enties from your file which contains clearly less than 1000 integers.
The first values of your array must be correct, but after you reach the end of your file the operator>> will not ready anything.
For example here is one way to write it:
const char* filename= "TestData.txt";
std::vector<int> myArray;
std::ifstream file(filename);
if(file.is_open())
{
int v;
while(file >> v) {
myArray.push_back(v);
}
}
int if I'm not wrong can keep data from -32768 to 32767.
So if u have bigger values than that (which you have, from your source file), you won't have the results you are expecting.
btw, it would be nice to know also what output you are getting.

Saving char in a file problems

Hey.
I have some problems writing char to a file with ofstream.
this is how the code looks (Just to show how it works. This is NOT the real code).
char buffer[5001];
char secondbuffer[5001];
char temp;
ifstream in(Filename here);
int i = 0;
while(in.get(secondbuffer) && !in.eof[])
{
i++;
}
for(int j = 0; j < i; j++)
{
secondbuffer[j] = buffer[j];
}
ofstream fout(somefile);
fout << secondbuffer;
// end of program
The problem is that it reads the characters of the first file fine, but when it writes to the second file, it adds all characters from the first file, as its supposed to do, but when there are no more characters, it adds a lot of "Ì" characters in the end of file.
fx:
file 1:
abc
file 2:
abcÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ...
How can I prevent the program save "Ì" in the file?
EDIT2:
int i = 0;
lenghtofFile++;
while(fin.get(firstfileBuffer[i]) && !fin.eof())
{
i++;
lenghtofFile++;
}
firstfileBuffer[i] = '\0';
for(int j = 0; j < lenghtofFile; j++)
{
if(secondfileBuffer[j] != ' ' && secondfileBuffer[j] != '\0')
{
secondfileBuffer[j] = function(key, firstfileBuffer[j]);
}
}
secondfileBuffer[lenghtofFile]='\0';
fout << secondfileBuffer;
You need to null-terminate secondbuffer. You are adding all the characters read from the stream, which do not include the trailing NULL.
on the line before fout, add
secondbuffer[j]='\0\';
The problem is that there is no terminating null character in your file. When you read the file in, you get "abc" just fine, but the garbage that was sitting in secondbuffer when it was declared is still there, so writing "abc" to the beginning of it means that you have a 5001-length array of garbage that starts with "abc."
Try adding
secondbuffer[i] = '\0'; after your for loop.
This should work fine:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char buffer[5001];
char secondbuffer[5001];
ifstream in("foo.txt", ifstream::in);
ofstream fout("blah_copy.txt");
do
{
in.getline(buffer,5001);
fout<<buffer;
}
while(!in.eof());
in.close();
fout.close();
return 0;
}