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
If provided with command line argument argv[], what is a way to determine whether or not that input is a file name.
E.g. If we are entering ex.txt into the command line, and printing out the contents, how can I write a conditional statement to determine whether the input for argv[1] is correct?
Thanks. Let me know if I was too vague. This is my first post, and english is not my first language.
You probably don't want to know only whether the file exists but also if you can open and read it. The only reliable way (And, by the way, the only way currently supported by standard C++.) to do this is to try opening the file and see if you succeed.
#include <fstream>
#include <iostream>
int
main(const int argc, const char *const *const argv)
{
for (int i = 1; i < argc; ++i)
{
std::ifstream istr {argv[i]};
if (!istr)
{
std::cerr << "error: " << argv[i] << ": cannot read file\n";
continue;
}
// Do something with the stream...
}
}
Be aware that if you close the file after verifying that it is good, there is no guarantee that it will still be good if you try to open it again later. Some other process could have deleted it or taken your permissions to read it.
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 4 years ago.
Improve this question
I need to organize infinite loop with symbol analysis in it. In C I used fgets(buf, N, stdin), suppose buf is buf[10]. User could type string of any length and I could analyze it by breaking down the input and examining parts of length 10. How can I implement this in C++ without using C libraries. Sorry for my English if you can't understand what I mean
In C++ you should std::cin to read from standard input.
// #include <iostream>
do
{
char buf[10]{}; // create array of 10 bytes filled with zeros.
std::cin.read(buf, 10); // read 10 bytes
// at this point you should check if std::cin.read succeeded.
// otherwise you will be reading zeros.
std::streamsize numRead = std::cin.gcount(); // obtain number of read bytes.
std::cout << numRead << " " << buf << std::endl; // some printing.
}while(std::cin);
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 5 years ago.
Improve this question
I am currently reading a book that is teaching me about C++ and I have run into a problem. I looked around the Internet a bit to see if I can find an answer but I don't seem to understand them to well. I wrote this code...
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
// Writing the poem
string poem = "\n\tI never saw a man who looked";
poem.append("\n\tWith such a wistful eye");
poem.append("\n\tUpon that little tent of blue");
poem.append("\n\tWhich prisoners call the sky");
// More stuff
ofstream writer("poem.txt");
if(!writer) {
cout << "Error opening file for output" << endl;
return -1; // Signal a termination
}
writer << poem << endl;
writer.close();
// Teminates the program
return 0;
}
I think the problem specifically is this line writer << poem << endl;. But I am not sure what it is I am doing wrong. I am fairly certain I did the exercise correct.
Let me restate my issue. I have a text file that is generated with a poem. What I am trying to do is output the lines of text in the file to the console (terminal). The book that I am reading to do writer << poem << endl;. I did that but nothing is output, it just generates the file with the text and thats it.
A few long moments later.
As it turns out I was just being dumb and I later realized that the problem was more of me not reading/understanding the text to it's fullest. I was under the impression that this code was meant to output the text. I was wrong, but the following answer really helped me! Thanks.
Class ofstream writes to files not to the screen so to get the content of the file to your program then use class ifstream.
In your program if you want the text to be written to a file then read back to your program:
add this code right after closing the file after writting writer.close():
ifstream inFile("poem.txt");
string sLine;
while(getline(inFile, sLine))
cout << sLine << endl;
inFile.close();
Or simply use an object of class fstream doing the two tasks once: writting/reading.
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 6 years ago.
Improve this question
I have a program on a Linux system that generates data log files with predictable file names that I need to access, but I have to do so through a C/C++ interface. The program accessing the data needs to be able to take a file path with a regex to specify certain file name ranges and do the following:
Determine if there are files matching the regex that exist
Determine the total size of all of the matching files
I'm using these as checks before I compress and transfer the files. How can I do this in C/C++?
You could do something like this:
#include <regex>
#include <string>
#include <experimental/filesystem>
// make using it sane
namespace fs = std::experimental::filesystem;
int main(int argc, char** argv)
{
// default to current directory
fs::path dir = argv[1] ? argv[1] : ".";
fs::directory_iterator dir_ent{dir};
fs::directory_iterator dir_end;
std::regex e{R"~(.*\.txt)~"};
std::smatch m;
decltype(fs::file_size("")) total_size = 0;
for(; dir_ent != dir_end; ++dir_ent)
{
// for some reason regex_match won't accept temporaries
std::string s = dir_ent->path().string();
if(!std::regex_match(s, m, e))
continue;
// deal with filepath here
total_size += fs::file_size(dir_ent->path());
// etc...
}
}
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 8 years ago.
Improve this question
How could I access a text file and go through word by word. I understand how to open the file but just not how to pull out each word one by one. I think it has something to do with arrays?
Simply:
#include <fstream>
#include <iostream>
int main()
{
std::fstream file("table1.txt");
std::string word;
while (file >> word)
{
// do whatever you want, e.g. print:
std::cout << word << std::endl;
}
file.close();
return 0;
}
word variable will contain every single word from a text file (words should be separated by space in your file).
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've got a class:
class DataBase{
private:
fstream db_file;
public:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
}
void couteverything(){
string line;
if(db_file.good() && db_file.is_open()){
getline(db_file, line);
cout << line;
cout << "ok";
}
}
~DataBase(){
db_file.close();
}
};
and a file db.txt with some content.
I'd like to cout it to the console, but it's not working - as if the file was empty (nothing appears on the screen).
In your constructor, you do not test whether the file opened successfully. Therefore, you have no idea if the file opened successfully. Thus, your couteverything method can't distinguish EOF from "failed to open." You might consider adding a check:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
if (!db_file.is_open() || !db_file.good()) {
// put an error message here, or throw an exception. Up to you.
}
}
Once you're in couteverything(), presumably you want to loop over the entire file. You need a loop for that, not an if statement. Something like this:
while (getline(db_file, line)) {
cout << line;
cout << "ok";
}
Even if you did not want to loop here (in which case coutnextline() might be a better name for the method), you still want to test the result of getline() directly, rather than testing good() and is_open() before each read. You need to test whether getline() succeeds, otherwise your code will try to process one line beyond EOF or a read error.
if (getline(db_file, line)) {
cout << line;
cout << "ok";
}
If you do only want to output a line at a time, I'm not sure how the code that calls this would know when to stop. But, that's a different problem. (Hint: You could solve that by returning a bool from this line-at-a-time method.)