inFile - reading different files - c++

I am curious to know from the more experienced c++ programmers out there if there is a way to have a function read in files that have different formats. Example is one file has a template of house # then street name and the other file is the opposite, house name then street #. Again, just curious if there was some sleek code that I could add to my knowledge and tool box, instead of writing two different inFile functions.
Thank you all for your time.
EDIT
Here is some of the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct WH
{
int inum;
string iname;
string warname;
int quant;
float whole;
float markup;
float retail;
};
void readinprime(WH);
ifstream inFile;
ofstream outFile;
int main()
{
WH ware[100];
//inFile.open("WLL1.txt", ios::in);
//inFile.open("WLL2.txt", ios::in);
//inFile.open("WLL3.txt", ios::in);
//inFile.open("WLL4.txt", ios::in);
return 0;
}
void readinprime(WH ware[])
{
int c;
for(c = 0; c < 100; c++)
{
inFile << ware.inum[c] << ware.iname[c];
}
}
So essentially the first file (WLL1.txt) has the format integer->string and then the next file (WLL2.txt) will have the format string->integer. My question is, is there another way to write the read in function where it can read in int then string & string then int without writing another function? I dont mind writing another function for every file format, but I was just curious if someone had some good tricks that I could add to my tool box. Again thank you for your time.

you can use the getline method to read every line from the text and store it in a variable

Related

.write() not working in file handling c++ [duplicate]

I want to write a std::string variable I am accepting from the user to a file. I tried using the write() method and it writes to the file. But when I open the file I see boxes instead of the string.
The string is only a variable length single word. Is std::string suitable for this or should I use a character array or something.
ofstream write;
std::string studentName, roll, studentPassword, filename;
public:
void studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
filename = roll + ".txt";
write.open(filename.c_str(), ios::out | ios::binary);
write.put(ch);
write.seekp(3, ios::beg);
write.write((char *)&studentPassword, sizeof(std::string));
write.close();`
}
You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()
If you have fmt available:
#include <fmt/os.h>
// ...
fmt::output_file(filename).print("{}\0\0{}", ch, studentPassword);
// ...
But you are not really writing a password to a file, right?

Convert ASCII file to Binary format in C++

First, I would like to express that I come to post my question, after a lot of searching on the internet, without finding a proper article or solution to what I'm looking for.
As mentioned in the title, I need to convert an ASCII file to Binary file.
My file is composed of lines, every line contain float separated by space.
I found that many people use c++ since it's more easy for this kind of task.
I tried the following code, but the generated file is so big.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
char buffer;
ifstream in("Points_in.txt");
ofstream out("binary_out.bin", ios::out|ios::binary);
float nums[9];
while (!in.eof())
{
in >> nums[0] >> nums[1] >> nums[2]>> nums[3] >> nums[4] >> nums[5]>> nums[6] >> nums[7] >> nums[8];
out.write(reinterpret_cast<const char*>(nums), 9*sizeof(float));
}
return 0;
}
I found those 2 resources :
http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html
https://r3dux.org/2013/12/how-to-read-and-write-ascii-and-binary-files-in-c/
I appreciate if you have any others resources ?
lines in my ASCII input file are as below :
-16.505 -50.3401 -194 -16.505 -50.8766 -193.5 -17.0415 -50.3401 -193.5
Thank you for your time
Here is a simpler method:
#include <iostream>
#include <fstream>
int main()
{
float value = 0.0;
std::ifstream input("my_input_file.txt");
std::ofstream output("output.bin");
while (input >> value)
{
output.write(static_cast<char *>(&value), sizeof(value));
}
input.close(); // explicitly close the file.
output.close();
return EXIT_SUCCESS;
}
In the above code fragment, a float is read using formatted read into a variable.
Next, the number is output in its raw, binary form.
The reading and writing repeat until there is no more input data.
Exercises for the reader/OP:
1. Error handling for opening of files.
2. Optimize the reading and writing (read & write using bigger blocks of data).

Putting a String from a text into an array, using scanf

I'm having some problems reading a string into an array. my file contains the following strings running horizontally down the page.
File:
dog
cat
rabbit
mouse
Code:
#include <string>
int i = 0;
using namespace std;
int main()
{
FILE * input1;
fopen_s(&input1, "C:\\Desktop\\test.dat", "r");
string test_string;
while (!feof(input1)) {
fscanf_s(input1, "%s", test_string);
i++;
}
return 0;
}
Any advice would be appreciated, Thanks!
You should use ifstream and std::getline
Now, I'm going to walk you through reading lines from the file using ifstream
Include fstream to use ifstream.
#include <fstream>
Opening a file:
To open a file, create an object of ifstream, and call it's method open and pass the filename as parameter. ifstream opens a file to read from it. (To write in a file, you can use ofstream)
ifstream fin;
fin.open("C:\\Desktop\\test.dat");
Or you can simply pass the filename to the constructor to create an object of ifstream and open a file.
ifstream fin("C:\\Desktop\\test.dat");
Reading from the file:
You can use stream extraction operator (>>) to read from the file, just like you use cin
int a;
fin >> a;
To read a line from a file using the above created fin (using a char array)
char arr[100];
fin.getline(arr, 100);
Better yet, you should use std::string instead or char arrays, using std::string, you can read a line using std::getline
string testString;
getline(fin, testString);
Now, let's change your code to use ifstream and getline
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
ifstream input1;
input1.open("C:\\Desktop\\test.dat");
string test_string;
while (getline(input1, test_string)) {
i++;
}
return 0;
}

FStream - Reading Integers inside file C++

The objective is to read each integer in the following file and add them all up. But it seems I cannot cast the string line to an int for some reason.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string line;
ifstream file ("Random.txt");
int lines;
int amount = 0;
while(getline(file, line)){
lines++;
amount += static_cast<int>(line);
}
cout << amount;
return 0;
}
Txt file:
2
3
4
6
Any help would be much appreciated
No, you can't cast a string like that to anything, really.
If you know that the file contains only integers, you can just read them directly:
int number;
while (file >> number)
{
++lines;
amount += number;
}
A cast isn't the right tool to do so, it works for compatible types only.
What you actually need is a conversion function:
amount += std::stoi(line);
See the reference docs please.

How can I convert a text file with numbers in it into a binary file?

So I have made a program that opens up a text file using ifstream. Now I want to make it so it outputs this file in binary. I have tried ofstream and using .write() but when I do the program crashes. I set it up correctly when using .write() as I have seen online but I haven't seen anyone do it with what I was working with. Anybody have a solution to this? Also, I do not know why 'InputFile' and 'OutputFile' are both highlighted blue like that.
#include <iostream>
#include <fstream>
#include <string>
#include <bitset>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Error 1";
return 0;
}
else
{
int WIDTH, HEIGHT;
ifstream InputFile;
InputFile.open(argv[1], ios::in);
ofstream OutputFile;
OutputFile.open("OUTPUT.raw", ios::binary | ios::app);
cout << "Enter Width" << endl;
WIDTH = cin.get();
HEIGHT = WIDTH;
for (int x = 0; x < WIDTH; x++)
{
for (int y = 0; y < HEIGHT; y++)
{
OutputFile.write((char*)InputFile.get(), sizeof(InputFile));
}
}
}
//cout << bitset<8>(txt[i]);
return 0;
};
OutputFile.write((char*)InputFile.get(), sizeof(InputFile));
First, istream::get() extracts one characters from the stream and returns its value casted to an integer. The result is a temporary, which you cast to a pointer to char! It compiles, because the C-style cast basically tells the compiler "shoosh, I know what I'm doing!", but it will certainly do weird things at run-time. You need to get an adress of some object where the value you want to write is stored in, and cast that adress.
The second thing, sizeof(InputFile) returns size of ifstream class that manages the file stream. It's not in any way related to how many data is in the stream's buffer.
If you open a stream in text mode, then the correct way to extract data from it is to use extraction operator (>>). Then it's pretty simple:
std::ifstream in_file("numbers.txt");
std::ofstream out_file("numbers.bin", std::ios::binary);
int i;
while (in_file >> i)
out_file.write(reinterpret_cast<char*>(&i), sizeof(int));
The above snippet will work with an input text file like this: -4 21 1990 5425342 -3432 0 100.
You will have to parse your text file to get int for every string in file and just create a new file and write your binary data with fputc() or fwrite() functions.