I'm trying to read a text file but nothing is coming out. I feel like maybe It's not linking correctly in my Visual Studio Resources folder but if I double click it - it opens fine in visual studio and it doesn't run into any problems if I test to see if it opens or if it is good. The program compiles fine right now but there's not output. Nothing prints to my command prompt. Any suggestions?
Code
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
char str[100];
ifstream test;
test.open("test.txt");
while(test.getline(str, 100, '#'))
{
cout << str << endl;
}
test.close();
return 0;
}
Text File
This is a test Textfile#Read more lines here#and here
You try to open file by name without path, this means the file shall be in current working directory of your program.
The problem is with current directory when you run your program from VS IDE. VS by default sets current working directory for runnning program to project directory $(ProjectDir). But your test file resides in resources directory. So open() function could not find it and getline() immediately fails.
Solution is simple - copy your test file to project directory. Or copy it to target directory (where your program .exe file is created, typically $(ProjectDir)\Debug or $(ProjectDir)\Release) and change working directory setting in VS IDE: Project->Properties->Debugging->Working Directory, set to $(TargetDir). In this case it will work both from IDE and command line/Windows Explorer.
Another possible solution - set correct path to file in your open() call. For testing/education purposes you could hardcode it, but actually this is not good style of software development.
Not sure if this will help but I wanted to simply open a text file for output and then read it back in. Visual Studio (2012) seems to make this difficult. My solution is demonstrated below:
#include <iostream>
#include <fstream>
using namespace std;
string getFilePath(const string& fileName) {
string path = __FILE__; //gets source code path, include file name
path = path.substr(0, 1 + path.find_last_of('\\')); //removes file name
path += fileName; //adds input file to path
path = "\\" + path;
return path;
}
void writeFile(const string& path) {
ofstream os{ path };
if (!os) cout << "file create error" << endl;
for (int i = 0; i < 15; ++i) {
os << i << endl;
}
os.close();
}
void readFile(const string& path) {
ifstream is{ path };
if (!is) cout << "file open error" << endl;
int val = -1;
while (is >> val) {
cout << val << endl;
}
is.close();
}
int main(int argc, char* argv[]) {
string path = getFilePath("file.txt");
cout << "Writing file..." << endl;
writeFile(path);
cout << "Reading file..." << endl;
readFile(path);
return 0;
}
Related
This is not a duplicate. I'm trying to print some output to a file in a subdirectory (in this case to a file /stuff/output_1.txt) but it doesn't seem to create any new file. The code executes but no file is created, nor any subdirectory called /stuff. Here is my code:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main(void)
{
int out = 1;
stringstream fname;
fstream f;
fname << "./stuff/output" << "_" << out << ".txt";
f.open(fname.str().c_str(), ios_base::out);
f << "hello" << "\t";
f << endl;
f.close();
}
When I instead use the line
fname << "output" << "_" << out << ".txt";
It creates a file called output_1.txt in the current directory so the rest of the code clearly works. What is going wrong?
I'm on macOS so the "/" should be correct instead of the "\" used on Windows, no?
no file is created, nor any subdirectory
You are using fstream which expects the path to exist. If you are referencing a directory and it doesn't exist, then it will fail, because either you have to create the directory before you run your program, or you have to use mkdir() to create it.
You can check with f.is_open() if your stream could be opened.
f.open(fname.str().c_str(), ios_base::out);
if (f.is_open())
{
f << "hello" << "\t";
f << endl;
f.close();
}
else
std::cerr << "Unable to open " << fname;
nor any subdirectory called ./stuff
Why did you expect fstream to create subdirectories for you ? You have to do that yourself. I got the same behaviour when testing it on my machine, and the simple solution was to do a mkdir stuff. After that, the file got correctly created. But I think it's weird no runtime error is thrown. It's not good (especially for beginners) that fstream jsut silently does nothing when the subdirectory is not existing.
I am trying to open a text file, and the code below is my attempt:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
std::ifstream file;
file.open("InputFile.txt");
std::string fileOutput;
if (file.is_open())
{
while (!file.eof())
{
file >> fileOutput;
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File failed to open" << std::endl;
}
file.close();
return 0;
}
The text file is located on my desktop, and it only contain two integers.
Whenever I run the code above, it will show me the "file failed to open" message. I am completely new to c++, so I really don’t have any idea why my code is not working. So any comments would be appreciated.
The text file is located on my desktop
So where is your C++ source file, is it located in my desktop as well?
Note this code file.open("InputFile.txt"); tries to open the InputFile.txt in the current folder, that means it only works if both C++ source file and your text file are in the same folder. That seems to be your problem.
Like #ShadowRanger's this comment, the existing answers are both inaccurate. The argument for file.open() needs to either 1. reflect the relative location of the text file in relation to the current working directory (where you are calling the executable from), or 2. give the absolute location of the text file on the disc.
I suggest the following solution:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "incorrect number of inputs" << "\n";
std::cout << "correct usage: this_executable.exe file_location" << "\n";
return -1;
}
std::ifstream file;
file.open(argv[1]);
std::string fileOutput;
if (file.is_open())
{
while (file >> fileOutput)
{
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File "<< argv[1] <<" failed to open" << std::endl;
}
file.close();
return 0;
}
This solution takes the file's address info out of the code. With this solution, when you call your executable, the file's address(directory path + file name) is given to the executable at run-time rather than compile-time. Now, you'd run the executable like:
C:\path_to_your_exe>my_executable.exe C:\path_of_your_txt_file\InputFile.txt
The benefits of this approach are:
You can change the file's name / path without having to recompile the code;
On the commandline, it is easier to check that the target file's address is correct by tab completion
Also note:
As #ShadowRanger also pointed out the Why is “while ( !feof (file) )” always wrong? issue which I was not aware of.
If you are wondering what argv[1] means, see this guide for more information on commandline arguments for C++. You also want to make sure to catch situations when the user did not specify an input (meaning argv[1] is invalid, thus the argc != 2)
Unless the file you are opening and your executable are in the same directory, the same message will be printed since it will search for the file in the current working directory. You can specify the absolute path to the file on your desktop using %USERPROFILE%\\Desktop\\InputFile.txt or any other environmental variable that maps the absolute path of a disk, from which your file can be found.
I need to pass the value of one of the variables(containing the value of a path) to the contents of the file I am writing. The file outfile is of type ".ctl"
Lets say the file "outfile.ctl" gets created at location /abc/xyz
so I will be having /abc/xyz/outfile.ctl at this location. Now inside outfile.ctl file I have written some context. If you see the contents carefully I have included the line: file <<"file='filepath/Trial.data'\n"; which creates another file with the name Trial.data in the location filepath.Lets says filepath = /pqr/stu. So Ideally after the outfile.ctl file compiles I should have trial.data created at /pqr/stu llocation. I want to achieve this by the system command. But not getting the desired result created.Elaborated code is below
Snippet of the code.
void somefunc()
{
fstream file_1;
char outfile1[120],
filename[50] = "/abc/xyz/outfile.ctl";
char filepath[50] = "/pqr/stu/;
strcpy(outfile1, filename);
cout << outfile1;
cout << "\n";
file_1.open(outfile1, ios::out);
if (file_1) {
file_1 << "export\n";
file_1 << "client=000\n";
file_1 << "file='" << filepath << "/Trial.data'\n";
file_1 << "delete from BDRGIN\n";
file_1 << "select * from BDRGIN\n";
file_1.close();
system("R3trans outfile1");
}
Ideally the last line should create the trial data file in /pqr/stu/ folder but it doesnt. In my case it doesnot happen so , and a file outfile_1(without file extension) gets created in the folder where I am running the .cpp script. Can someone help?
It's not hard
file << "file='" << filepath << "/Trial.data'\n";
In C++ variables don't get substituted inside strings (unlike some scripting languages).
EDIT
You have basically made the same mistake again with your system command, variables don't get substituted inside strings. If you need a string variable which is made from other string variables you have to build up the string using strcpy and strcat. Try it like this
char cmd[250];
strcpy(cmd, "R3trans ");
strcat(cmd, outfile1);
cout << cmd << "\n"; // for testing
system(cmd);
You are missing a couple of things which I added:
You didn't include the output filename and filepath variables into your code, you didn't post all of your code to make in compilable.
Below is the code with "current path" (which we obtain with cwd in Linux) and your filename, included into your file "Trial.data" and written to the "current path/Trial.data" in you compile directory.
#include <iostream>
#include <fstream>
#include <string.h> //for strcat to concatinate the two (filepath+filename)
#include <unistd.h> //for getcwd to obtain your 'current path'
using namespace std;
int main(){
fstream file;
char cwd[256];
char *filepath= {getcwd(cwd, sizeof(cwd))}; // or write your path here instead
char filename[15] = "/Trial.data";
strcat(filepath, filename);
file.open(filepath,ios::out);
if(!file){
cout<<"File creation failed";
} else {
cout<<"New file created";
file <<"export\n";
file <<"client=000\n";
file <<"file='" << filepath << "'\n";
file <<"select * from HTTPURLLOC\n";
file.close(); // Step 5: Closing file
}
return 0;
}
I am new to C++.
I was trying to read a file using fstream.
here is the code,
I put the file inside the a.out directory but still cannot read it, where is my mistake?
#include<iostream>
#include<fstream>
int main()
{
std::ifstream myfile("my.txt");
int a, b;
while(myfile>>a>>b)
std::cout<<a<<b;
return 0;
}
Try:
#include <iostream>
#include <fstream>
#include <unistd.h>
int main()
{
char* name = get_current_dir_name();
std::cout << "Current Working Dir: " << name << "\n";
free(name);
std::ifstream myfile("my.txt");
if (!myfile))
{
std::cout << "Failed to open file\n";
exit(1);
}
int a, b;
while(myfile>>a>>b)
{
std::cout<<a<<b;
}
return 0;
}
Make sure that the file is located in the current directory of the .exe. This is usually the same directory as where the .exe is located on your harddrive.
If you don't know what the current directory is, I recommended you use the full path.
I'm trying to write a program to parse the first and sixteenth columns of a CSV file (converted into .txt). I have the CSV ("posts.txt") document in the folder with the executable. But, whenever I try to run the executable, my program delivers that it cannot open the file (or that "!infile.is_open()"). Mind giving me some assistance? I'm running in Xcode 3.2.3 on Mac OSX 10.8.3. The code is shows below.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string.h>
using namespace std;
void answeredPostGrabber()
{
ifstream inFile("posts.txt");
string postNumber;
string answerNumber;
string throwAway;
if(inFile.is_open())
{
while(inFile.good())
{
getline(inFile,postNumber,',');
cout << postNumber << ",";
for(int y=1;y++;y<16)
{
getline(inFile,throwAway,',');
}
getline(inFile,answerNumber,',');
cout << answerNumber << endl;
ofstream edges;
edges.open("edges.txt",ios::app);
edges << postNumber << "," << answerNumber<< endl;
edges.close();
ofstream nodes;
nodes.open("nodes.txt",ios::app);
nodes << postNumber << "\n" << answerNumber << endl;
nodes.close();
getline(inFile,throwAway);
}
}else cout << "ERROR: Unable to open file." << endl;
}
int main ()
{
answeredPostGrabber();
return 0;
}
Thank you in advance!
I have the CSV ("posts.txt") document in the folder with the executable.
The file should be present in the current working directory of your process, which may or may not be the same directory where the executable lives. If in doubt, try specifying the full path in ifstream inFile(...); to see whether that changes things.
Additionally, the file needs to have the correct permissions to ensure that it's readable by the process.