Transfer contents from C FILE to C++ stream [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Suppose I have a file opened with the C syntax
FILE* fp = fopen("whatever.txt", "w");
// Library function needs FILE* to work on
libray_function(fp);
// Now I'd like to copy the contents of file to std::cout
// How???
fclose(fp);
I would like to be able to copy the contents of that file in a C++ ostream (like a stringstream or maybe even std::cout). How can I do that?

You could use an ifstream and rdbuf():
#include <fstream>
#include <sstream>
std::ifstream in("whatever.txt");
std::ostringstream s;
s << in.rdbuf();
or:
std::ifstream in("whatever.txt");
std::cout << in.rdbuf();

You've opened the file for write. You're going to need to close it and reopen it anyway, you might as well open it however you please (as an istream if you like). Then it just depends how much you care about performance. If you actually care, you should read it in chunks (at least 512 bytes at a time). If you don't care about performance you can read one byte, spit out one byte.

Close it first.
fclose(fp);
Then open again
string line;
ifstream myfile ("whatever.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}

Related

Saving results to a file in C++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a problem with this code.
What I am looking for in the code is to get the result of "first" and "second" randomly and put the result in a file.
It works great if I run it without using the file and I get all the correct results, but when I try to save the result in the file, I get only the first node which contains (first, secnd).
Here is the code:
#include<iostream>
#include <fstream>
#include<cmath>
using namespace std;
void main()
{
int first[100],secnd[100];
for (int i=0; i<100 ;i++)
{
first[i]=rand()%500; //random number from to 499
secnd[i]=rand()%500; //random number from to 499
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile <<first[i]<<" "<<secnd[i];
myfile.close();
}
}
You are opening your file in the wrong place. You open the file once before the loop and close the file once after the loop. Like this.
myfile.open ("example.txt");
for (int i=0; i<100 ;i++)
{
...
}
myfile.close();
When you open a file for output you delete what is currently in the file. So if you open the file inside the loop then you are losing the random numbers you had written before.
The default open-flags for an ofstream are to truncate (overwrite) the file. You are opening and closing the file every time through the loop. If you want all results in the file, then open it ONCE outside the loop, and close it after the loop.
You're reopening the file in the loop. This zeros the file each time, so you only get the last entry.

characters and files in C++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have to make a program where the filename is composed of two parts: the first one is fixed and the second one can change during the program e.g "fixpart_integer.dat". I tried to do this in C++ but I did not succeed. The fisrt probelm is: how can i convert a number to a char ; and how can i concanate these 2 characters ; and how to declare this final char in the right way in order to open this filename ?
Many questions but I did find an easy way to do this.
#include <string>
#include <sstream>
std::string make_filename(std::string prefix, int id) {
std::stringstream ss;
ss << prefix << "_" << id << ".dat";
return ss.str();
}
and then I convert the string to char.
if you are working with c you may try the function described in here itoa
else if you are working woth c++ you may try something like this:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

how would one go about finding specific words in a text file in c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
how would i do this:
Got a text file called directorycontents.txt in this directorycontents.txt there is a bunch of text each one is a filename with a filename extension i want to be able to go like this if there is a filename extension of specific characters like .txt or .png then do fprintf(stderr,"whateva");
i have looked at istream and fstream and iostream but im not really shore how to use fstream to do this
thanks
Okay, I'll just point you to the right direction and I won't post any code, as you need to try it by yourself.
First of all, read about reading files in C++. You can google it and there are tons of information about this. You can try with "how to read text file in C++", for example.
Second, prefer using ofstream and/or ifstream - this is the C++ way to do it.
Then parse the file - you can read it word by word (using istream::operator>> ) , line by line (for example with getline ) into std::string (as you're talking about file names).
And then analize the input - analize the parsed file and search for specific words in it - for example, std::string has member functions like find - I think this will be enough for your problem :)
I hope that helps. Just note, that we don't write code here, we just help finding solutions for problems.
For something like this definitely take a look at std::fstreams. Based on your vague description of what you're trying to do, you can use this simple program as a starting point:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void doSomething();
int main(int argc, char *argv[])
{
if(argc < 2)
{
cout << "Usage: findsomething [filename]" << endl;
return 1;
}
ifstream infile(argv[1], ifstream::in);
if(!infile.is_open())
{
cout << "Couldn't open file " << argv[1] << endl;
return 1;
}
string line;
while(getline(infile, line))
{
if(line.find(".txt") != string::npos ||
line.find(".png") != string::npos ||
line.find(".bat") != string::npos)
{
doSomething();
}
}
}
Hopefully, that's enough code to get you started and it isn't too difficult for you to read.

c++ textfile borland [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I ask about the function that seek in the K-th line in a text file and the one that read the text file by line or by character in C++! knowing that i'm working with borland.
fpeek is an open source application that does exactly that. Check the sources and see how its done.
I took a quick look and I believe you'll end up with something like this (I haven't tested this code):
std::ifstream file(filename);
std::string line;
int pos = 1;
while (std::getline(file, line))
{
// Find if current line should be displayed
if (15 == pos) // looking for the 15th line in the file
{
std::cout << pos << ": " << line << std::endl;
}
pos++;
}

Problems with garbage characters when reading file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I'm having trouble reading data from a file, and concatenating selected parts of the data (text) into a buffer of my own.
The code is like follows:
char buffer[1000];
char* allNewData = (char *)malloc(10000);
while (! myfile.eof() )
{
myfile.getline (buffer, 1000);
pch = strstr (buffer,"bla bla");
if(pch == NULL)
{
char* temp = buffer;
strcat(allNewData, temp);
strcat(allNewData, "\n");
}
else
{
strcat(allNewData, "here's bla bla");
strcat(allNewData, "\n");
}
}
cout<<allNewData<<endl;
When I run the program, allNewData first has some garbage text, followed by the proper/expected results, like this:
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii <-rubbish data
hello <- actual data
I need to get rid of this rubbish data, how can I change the code to achieve this?
You need to clear your newly allocated buffer before using string concatenation functions. They expect a valid string, to be able to find the end and thus the start of where to concatenate.
Use:
allNewData[0] = '\0';
this makes allNewData into an empty string. Do this before the loop, before you start concatenating all the found data.
Also, your code needs to better take care of the various "gotchas" when it comes to I/O and handling memory:
Don't check for EOF before doing a read access.
Check that the read was successful, before using the results of the read.
Make sure you don't exceed the capacity of your buffer when storing data.
Some comments, which you may find helpful or disregard:
What if there is a line longer than 1000 characters? (and say, that 1001-1008 is 'blah blah')? The line will be split into two in your new file and there will be an extra line before "here's blah blah"? Is this now a bug or desired functionality?
What if the line is longer than 1000, but "blah" is 996-1000 and the second "blah" is on the second segment - now you've lost one
What if your file is longer than 10000 characters?
They may sound like trivial questions, but answering them correctly will mean that you'll have to change your approach, I suggest purer C++ approach:
ifstream f_in(<file>);
ostringstream s_out;
string line;
while(f_in.good())
{
getline(f_in, line); // global getline function in <string>
if (line.find("blah blah") != string::npos)
{
s_out << "here's blah blah" << endl;
}
else
{
s_out << line << endl;
}
}
This way you don't have to worry about any of the questions above...
You can also use a combination of getline and ignore
Again... you have to check that your IO operation don't fail and eof() should be used only after a failed IO operation.