how would one go about finding specific words in a text file in c++ [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 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.

Related

how to read data in c++ from a file stored in any other structure e-g: .text file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
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
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.
Improve this question
i gotta read data in c++ from a text file stored in computer
and then tokenize the data on the basis of space so that each word becomes a separate string
i have tried a code but it doesn't print anything as an output instead of a black blank screen
// basic file operations
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
//using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");``
myfile << "Writing this to a file.\n";
// myfile.close();`
getch();
return 0;
}
please help :(
The code you have posted does not attempt to write anything to standard output (std::cout). It opens a file (example.txt) and writes "Writing this to a file" in it, closes the file, and then waits for you to press a button before exiting the program. You are seeing no output because you've provided no output operations, nor does it attempt to read anything from the file.
First use ifstream since you want this file as input not output
Second what is this code you posted has to do with the question?
Try this:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("example.txt");
if (file.is_open())
{
std::string str;
while (std::getline(file, token, ' '))
{
//here str is your tokenized string
}
} else
{
std::cout << "Unable to open file";
}
}
getline will get the next string until the end of line or ' ' is met
This code WRITES to a file...maybe there's a C++ way to do it but strtok does what you describe.
Found within a minute of googling :)
using namespace std;
string STRING;
ifstream myReadFile;
myReadFile.open("Test.txt");
char output[100];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
getline(myReadFile,STRING);
cout << STRING;
}
myReadFile.close();
}
Edit: Fixed the thing and tested it with success.

Transfer contents from C FILE to C++ stream [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.
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();
}

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.

Saving many images with its dynamic name [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 need to save images captured from camera just like
"D:\storage\img1" then I press "s" another time and program should save
"D:\storage\img2" and then
"D:\storage\img3"
so everytime I press a custom key it will save an image with different name.
How to do that?
Thanks for all your responses
This code concatenates (adds) the value of int i to string filename. This is done through IntToStr() . And int i loops from 0 to 20 and thus creating your "dynamic name".
File output :
PhotoImage0.txt
PhotoImage1.txt
PhotoImage2.txt
..
..
PhotoImage19.txt
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
string IntToStr(int n)
{
stringstream result;
result << n;
return result.str();
}
int main ()
{
ofstream PhotoImageFile;
int Number_of_files=20;
string filename;
for (int i=0;i<Number_of_files;i++)
{
filename="c:\\PhotoImage" + IntToStr(i) +".txt";
cout<< filename << " \n";
PhotoImageFile.open(filename.c_str());
PhotoImageFile << filename<<" : Writing this to a file.\n";
PhotoImageFile.close();
}
return 0;
}
On startup, iterate the folder with an 'img*.*' mask - how you do this is up to your file system API. Use string functions or a loop to extract the part of the filename representing the number and convert it to an int. Every time you need to save a file, add 1 to the int, convert back to number-string & then concat the path, "img", number-string and extension to assemble the new file spec.

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.