Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to read and write binary data in C++.I use from ofstream and ifstream classes but it can't read some chars like 9,13,32.If is there another way to read and write theme.
Open the file using the std::ios::binary flag and then use .read(buffer,length); and .write(buffer,length); rather than the streaming operators.
There are some examples here:
https://cplusplus.com/reference/istream/istream/read/
https://cplusplus.com/reference/ostream/ostream/write/
Here is a program that does this:
#include <iostream>
#include <fstream>
int main(int argc, const char *argv[])
{
if (argc < 2) {
::std::cerr << "Usage: " << argv[0] << "<filename>\n";
return 1;
}
::std::ifstream in(argv[1], ::std::ios::binary);
while (in) {
char c;
in.get(c);
if (in) {
::std::cout << "Read a " << int(c) << "\n";
}
}
return 0;
}
Here is an example of it being run in Linux:
$ echo -ne '\x9\xd\x20\x9\xd\x20\n' >binfile
$ ./readbin binfile
Read a 9
Read a 13
Read a 32
Read a 9
Read a 13
Read a 32
Read a 10
This is a basic example (without any error check!):
// Required STL
#include <fstream>
using namespace std;
// Just a class example
class Data
{
int a;
double b;
};
// Create some variables as examples
Data x;
Data *y = new Data[10];
// Open the file in input/output
fstream myFile( "data.bin", ios::in | ios::out | ios::binary );
// Write at the beginning of the binary file
myFile.seekp(0);
myFile.write( (char*)&x, sizeof (Data) );
...
// Assume that we want read 10 Data since the beginning
// of the binary file:
myFile.seekg( 0 );
myFile.read( (char*)y, sizeof (Data) * 10 );
// Remember to close the file
myFile.close( );
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a problem because this is my first time encountering some functions from C that I need to convert into C++.
Code:
FILE *pokf;
char name[10],gender;
int age, i, n, b1=0, b2=0;
float p;
pokf=fopen("Data.txt","r");
while (feof(pokf)==0) {
fscanf (pokf,"%s %c %d %f", &name, &gender, &age, &p);
if (gender=='Z') b1++;
if (p>=4.50 ) b2++; }
fclose(pokf);
I can write:
ifstream input;
input.open("Data.txt");
But then I don't know what to use instead of pokf because I can't use FILE *pokf anymore.
What to use instead of functions feof and fscanf?
The rough equivalent of fscanf is operator>> and I wouldn't worry about feof since it's being used incorrectly. So
while (feof(pokf)==0) {
fscanf (pokf,"%s %c %d %f", &name, &gender, &age, &p);
...
becomes
while (pokf >> name >> gender >> age >> p) {
...
Although using char name[10] in C++ will work, it has the obvious problem that you are limited to names of 9 characters of less. In C++ you should use std::string instead of a char array.
You should be able to use FILE *pokf in c++, here is an example http://www.cplusplus.com/reference/cstdio/feof/ where you can see how to open files in c++
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to compare two columns in a word file which are filled with numbers row wise. For instance if there is a word file which has these two columns:
1 56
2 57
3 59
4 63
Then if I am giving the input 2 the output should be 57 in C C++. What logic will help in mapping a table and using its values?
Please help. So far I could not think of any approach. I am reading the file line by line using this piece of code.
#include <stdio.h>
int main(int argc, char* argv[])
{
char const* const fileName = argv[1]; /* should check that argc > 1 */
FILE* file = fopen("C:\\Users\\parth\\Downloads\\state_model_files.txt", "r"); /* should check the result */
char line[256];
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence would allow to handle lines longer that sizeof(line) */
printf("%s", line);
}
/* may check feof here to make a difference between eof and io failure -- network
timeout for instance */
fclose(file);
getchar();
return 0;
}
Basically what you want to do is (1) open the file, (2) grab a line from the file, (3) write the values of each column to some variable, and (4) store them into a map. Later on, you can make queries like the one you suggested in your post. Note, the approach below makes certain assumptions about your input data.
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
using namespace std;
int main(int argc, char *argv[]) {
ifstream in(argv[1]);
if(!in) {
cout << "Could not open file " << argv[1] << endl;
return -1;
}
map<int, int> m;
int c1, c2;
string fields;
while(getline(in, fields)) {
istringstream ss(fields);
ss >> c1 >> c2;
m[c1] = c2;
}
in.close();
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
everyone.
The program as shown below isn't executed for large text file, for example, 30GB.
The program is for simply converting text file format.
Let me know how to solve the issue.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include </usr/include/pcl-1.7/pcl/io/pcd_io.h>
#include <pcl/point_types.h>
int main (int argc, char** argv)
{
int r,g,b;
if(argc!=3)
{
fprintf(stderr,"Usage:%s\n(1)Input_XYZRGB_filename\n(2)Output_PCD_filename\n",argv[0]);
exit(1);
}
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
std::ifstream ifs(argv[1]);
std::string buf;
for(size_t i=0; ifs && getline(ifs, buf); i++)
{
// std::cout << buf << std::endl;
std::istringstream is(buf);
pcl::PointXYZRGB pnt;
is >> pnt.x
>> pnt.y
>> pnt.z
>> r
>> g
>> b;
pnt.r= (uint8_t)r;
pnt.g= (uint8_t)g;
pnt.b= (uint8_t)b;
cloud->push_back ( pnt );
}
pcl::io::savePCDFileASCII(argv[2], *cloud);
return 0;
}
Make sure that your file input/output library supports large files. You can read the documentation. Also check the size of the file position parameter in the seek operation. In order to support large files it has to be 64 bit, not 32. In MS Visual C++, standard iostream seems does not support large files. But you can use other, low level input/output functions: _sopen_s, _read, _close, _lseeki64, etc. In gcc and mingw, you can use functions: _sopen, read, close, lseek.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I want to represent my file as a string but I have a problem the file contains a 0x00 and my string gets terminated right there.How to solve this?
If you can't use the null as the termination character you have very few options:
a) write the string size prior to the string:
005Hello
011Hello\0World
b) use fixed length strings
c) prepend non-terminating nulls with a special char like '\'. If '\' appears in your string, write it twice "\". Reverse the logic when reading them back.
I have a txt file like this in binary 0x61 0x61 0x61 0x00 0x62 0x62 0x62
"txt file" in binary ? - I don't know what does it mean .
But if you have values separated by spaces you can try using std::vector of std::string
(which doesn't use null termination)
std::ifstream fin("input.txt");
std::vector<std::string> v;
std::copy(std::istream_iterator<std::string> (fin),
std::istream_iterator<std::string> (),
std::back_inserter(v) );
std::vector<std::string>::iterator it =v.begin();
for(;it!=v.end();++it)
std::cout<< *it<<" ";
Be sure to read your file in binary mode:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
std::string read_file_as_string(const char* filename) {
std::ifstream input(filename, std::ios::binary);
if (!input) {
std::perror("Great failure");
std::exit(1);
}
std::stringstream contents;
contents << input.rdbuf();
return contents.str();
}
int main() {
std::string s = read_file_as_string("Derp.exe");
std::cout << "s.size() = " << s.size() << '\n';
for(unsigned char c : s) {
std::cout << std::hex << static_cast<unsigned int>(c) << ' ';
}
std::cout << '\n';
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Say I have a text file containing 10 lines. I want to move to line #5, clear everything below it, and append some new texts after that. What is the most compact way to achieve this using C++ of stream (just in case I missed some ofstream features)?
Read N lines while writing to a second file, then write all the new text to the new file after that.
Use IOstream to open the file and store the first five lines in an array and recreate the test file using the array and whatever other lines you want. Here is a code example:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
const int linesToRead = 5; //How many lines to read before stopping
string lines [linesToRead];
int line = 0;
ifstream myinputfile ("example.txt");
if (myinputfile.is_open())
{
while ( myinputfile.good() && line<=linesToRead )
{
if(line<linesToRead)
{ //Stop reading at line 5
getline (myinputfile,lines[line]);
cout << lines[line];
}
line++;
}
myinputfile.close();
}
else cout << "Unable to open file";
//Begin creating new file
const int numberOfNewLines = 7;
string newlines[numberOfNewLines] = {"These", "are", "some", "of", "the", "new", "lines"}; //lines to be added after the previous 5
ofstream myoutputfile ("example.txt");
if (myoutputfile.is_open())
{
for(int i = 0; i<linesToRead; i++){
myoutputfile << lines[i] << "\n";
}
for(int i = 0; i<numberOfNewLines; i++){
myoutputfile << newlines[i] << "\n";
}
myoutputfile.close();
}
else cout << "Unable to open file";
return 0;
}