I have a C++ file that I would like to learn from but I am facing difficulty trying to open my text file which contains data to read. I am trying to figure out where do I put my text file.
My code is:
#include <fstream>
#include <cstdlib>
using namespace std;
void rFile(string argvFile);
void Init(int i, Chord& newChord);
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "INCORRECT SYNTAX!" << endl;
} else {
**//I changed the this to rFile("text.txt"); but error too.**
rFile(argv[1]);
}
}
void rFile(string argvFile) {
Chord newChord;
string inLine;
ifstream inFile;
**// I got an error trying to put the text file name after argvFile.c_str("text.txt"));**
inFile.open(argvFile.c_str());
if (inFile.is_open())
while (inFile.good()) {
getline(inFile, inLine);
}
} else {
cout << "ERROR! FOUND NOT FOUND!" << endl;
}
}
Can someone please kindly enlighten me?
This code reads filename from the program parameters,
rFile(argv[1]);
argv is an array of parameters passed to the program during its execution, so for example running
./prog a b c
assigns
argv[1] = "a"
argv[2] = "b"
argv[3] = "c"
the 0'th element (argv[0]) contains the program name, so in this case
argv[0] = "prog"
so in case of your program - once you compile it to the prog, you run it through (unix)
./prog PATH_TO_FILE
or (windows)
prog.exe PATH_TO_FILE
Related
I tried programming a file writer, but when i try to write to a file with something that has multiple words it will suddenly create files.
My code
#include <fstream>
#include <iostream>
#include <unistd.h>
int main(int argc, char *argv[]) {
char cwd[256];
while (true) {
getcwd(cwd, 256);
std::string cwd_s = (std::string)cwd;
std::string Input;
std::cout << cwd_s << "> ";
std::cin >> Input;
std::ofstream file(Input);
std::cout << "cmd /";
std::cin >> Input;
file << Input;
};
for (int i; i < argc; i++) {
std::cout << argv[i] << '\n';
};
return 0;
}
I expected to get this:
C:\Users\code> File.txt
cmd /hello world!
File.txt
hello world!
But it only had "hello", it created another file named world!
I have tried changing the code, but to no avail.
So I have wrote this code that I think does what you expect. The behavior you were seing is because you used the same string to store the filename and the user input. Also you redefined a new file every loop (without closing the previous one). I added a signal handler since if you press Ctrl+C the program would quit without saving/closing the file.
I added comments about how you can make a better CLI interface (if you're interested)
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
std::ofstream outfile;
void signalHandler(int signum) {
outfile.close();
exit(signum);
}
int main() {
char cwd[256];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
std::cout << cwd << "> ";
} else {
std::cerr << "Error: Could not get current working directory." << std::endl;
return 1;
}
std::string filename;
std::getline(std::cin, filename);
outfile.open(filename);
// We intercept the Ctrl+C signal to close the file before exiting. Else nothing will be written to it.
// You can also use Ctrl+D (EOF: End Of File) to exit the program.
// The best praticte would be to implement a command line interface with a "quit" command. (like a map<string, function> for example)
signal(SIGINT, signalHandler);
// Another good practice is to check if the file did open correctly.
if (!outfile.is_open()) {
std::cerr << "Error: Could not open file for writing." << std::endl;
return 1;
}
std::cout << "cmd / ";
char ch;
while (std::cin.get(ch)) {
outfile.put(ch);
if (ch == '\n') {
std::cout << "cmd / ";
}
}
outfile.close();
return 0;
}
Hope it will help you ! And if you have any question about the code feel free to ask I'll explain !
I'm trying to create a program that passes a file to a function. The function is supposed to detect how many lines are in my file. I don't think I'm passing the file correctly into my function, I've tried several different ways. Any help will be greatly appreciated.
#include <iostream>
#include <fstream>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_lines(ifstream file)
{
int cnt3;
string str;
while(getline(file, str))cnt3++;
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(ifstream file);
string file;
file = argv[1];
if(argc == 1)die("usage: mywc your_file"); //for some reason not working
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int a;
cout << "File was opened\n";
a = num_of_lines(file);
cout <<"Lines: " << a << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Two problems with the function. First, you should pass the stream by reference. Second, you just forgot to initialise your counter.
int num_of_lines( ifstream &file )
{
int cnt3 = 0;
string str;
while( getline(file, str) ) cnt3++;
return cnt3;
}
The other thing is you're passing file to it (which is a string) instead of ifs. Change the call to:
a = num_of_lines( ifs );
I have the following main method:
int main(string argf)
{
ifstream exprFile(argf);
string inExpr;
if (exprFile.is_open())
{
while ( getline(exprFile,inExpr) )
{
//do stuff
}
exprFile.close();
}
else cout << "Unable to open file";
system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}
I have run this program from the command line using the following:
"C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"
C:\Complete Filepath\Project2.exe C:\Differnt Filepath\args.txt
"C:\Complete Filepath\Project2.exe" "args.txt"
C:\Complete Filepath\Project2.exe args.txt
The last two with args.txt being in the same directory as the executable. All four gave the "Unable to open file" result. Attemping to print the argf value before doing anything with it yielded nothing at all. A completely blank print statement.
I then went into the Visual Studio 2010 options and added all variations of the args.txt file under the arguments section there with the file in different locations as well and nothing works.
What am I doing wrong?
How are you supposed to open a file passed as an argument on the command line?
int main ( int argc, char *argv[] )
This is correct way to get argument from main.
argc is number of arguments. argv is argument list.
Actual argument will start with index = 1. Value at index 0 will be always program name.
In your example,
"C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"
argc = 2
argv[0] = "Project2.exe"
argv[1] = "C:\Differnt Filepath\args.txt"
Yay, code!
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream exprFile;
string inExpr;
for( int i = 1; i < argc; i++) { // 0 is the program name
exprFile.open(argv[i]);
if (exprFile.is_open()) {
while ( getline(exprFile,inExpr) ) {
cout << "Doing stuff on line: " << inExpr << "\n";
}
exprFile.close();
}
else cout << "Unable to open file " << argv[i];
}
}
I am writing a simple program to take in two files. The terminal command line looks like this.
./fileIO foo.code foo.encode
When it runs, the second file is not read in. When I enter
./fileIO foo.code foo.code
it works. I can't seem to figure out why the second one is not opening. Any ideas? Thanks!
#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;
int main( int argc, char *argv[] )
{
// convert the C-style command line parameter to a C++-style string,
// so that we can do concatenation on it
assert( argc == 3 );
const string code = argv[1];
const string encode = argv[2];
string firstTextFile = code;
string secondTextFile = encode;
//manipulate the first infile
ifstream firstFile( firstTextFile.c_str(), ios::in );
if( !firstFile )
{
cerr << "Cannot open text file for input" << endl;
return 1;
}
string lineIn;
string codeSubstring;
string hexSubstring;
while( getline( firstFile, lineIn ) )
{
hexSubstring = lineIn.substr(0, 2);
codeSubstring = lineIn.substr(4, lineIn.length() );
cout << hexSubstring << ", " << codeSubstring << endl;
}
//manipulate the second infile
ifstream secondFile( secondTextFile.c_str(), ios::in );
if( !secondFile )
{
cerr << "Cannot open text file for input" << endl;
return 1;
}
char characterIn;
while( secondFile.get( characterIn ) )
{
cout << characterIn << endl;
}
return 0;
}
One thing you might want to try is adding the close() call as is standard procedure after you're done using files. Sometimes issues arise with re-opening files if they were not closed properly in a previous run.
firstFile.close();
secondFile.close();
Also, you may try restarting the computer if there is some lingering file handle that hasn't been released.
I'm trying to open a file using ifstream, but no matter what solutions I find that I've tried, nothing seems to work; my program always outputs "unable to open". Below is my code in its entirety. Any help at all is appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
string junk;
ifstream fin;
fin.open("somefile.txt");
if(fin.is_open())
{
fin >> junk;
cout << junk;
}
else
{
cout << "unable to open" << endl;
}
fin.close();
return 0;
}
Also, the contents of somefile.txt, which is in the same directory as the created executable is the following:
SOME
FILE
As some commenters have suggested, it could easily be that the file truly doesn't exist, because you're looking for it in the wrong place. Try using an absolute path to the file rather than just assuming it's looking where you expect.
And output a more helpful error message using strerror(errno).
// ...
fin.open("C:\\path\\to\\somefile.txt");
// ...
else
{
cout << "unable to open: " << strerror(errno) << endl;
}