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.
Related
I'm trying to figure out how to write to a file outside the working directory. This is the code I currently have.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string sp{};
std::fstream ss("C:\\Users\\onion\\AppData\\Roaming\\MetaQuotes\\Terminal\\some numbers\\MQL5\\Files\\testnew.txt", std::ios::in | std::ios::out);
if (!ss.is_open()) std::cout << "Failed" << '\n';
else
{
while (ss.is_open())
{
std::getline(ss, sp);
std::cout << sp << '\n';
ss << "new data";
if (ss.eof())break;
}
}
}
I can read the file perfectly fine, but I cant write to it? Could it be that Metatrader itself is limiting my ability to write to a file or does a file have to be in the working directory to be able to write to it? or am I just doing it wrong?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file;
file.open ("ernio.txt", ios::in);
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
It prints example instead of reading line by line from the file. What am I doing wrong?!? (the file is in the exact same place as the main.cpp) We even tried:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file("ernio.txt");
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
Please help
The file needs to be in the directory from where the executable will be called, not in the source directory where your main.cpp resides.
When you build small programs with gcc or something similar from the command line, often the executable is in the current working directory, where the compiler will also draw the source files from.
When using a build system or an IDE, however, then usually the target of a build is different from that where the sources reside.
I am trying to rename a file with the rename() function of stdio.h and it works but the problem is that it can only rename files located in the folder of the current project, I would like to be able to select a directory and if it is possible to change it from location in the process.
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
int main()
{
bool verifier;
char oldName[] = "text.txt";
char newName[] = "newText.txt";
verifier = rename(oldName, newName);
if (!verifier)
{
std::cout << "The file has been succesfully renamed\n";
}
else
{
std::cout << "There was a problem renaming the file\n";
}
return 0;
}
Thank you!
By default, the root directory path is the location which the executable is running in. If you want to access another folder above our outside that location, you can use an absolute path (ie C:/path/to/old.txt).
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
int main()
{
char oldName[] = "C:\\path\\to\\your\\proj\\text.txt"; // char oldName[] = "old.txt";
char newName[] = "C:\\test\\output\\folder\\new.txt"; // char newName[] = "newText.txt";
bool verifier = rename(oldName, newName);
if (!verifier)
{
std::cout << "The file has been succesfully renamed\n";
}
else
{
std::cout << "There was a problem renaming the file\n";
}
return 0;
}
Premise: I'm using CLion.
As i said in title, when i try to open a file (txt) nothing will be displayed.
i can't explain it, i don't think i made an error, it's pretty easy this code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
FILE *leggi;
leggi = fopen("lorem.txt", "r");
char datiLetti[1000];
while(fgets(datiLetti, 1000, leggi)!=NULL){
cout << datiLetti << endl;
}
fclose(leggi);
system("PAUSE");
return EXIT_SUCCESS;
}
file "lorem.txt" is in the same directory of the project.
Thank you in advance.
EDIT1: file is lorem not lorem_ipsum, my mistake when i typed here.
You want this:
...
FILE *leggi;
leggi = fopen("lorem.txt", "r");
if (leggi == NULL)
{
cout << "Can't open file" << endl;
return 1;
}
...
---FIXED---
Installed cygwig1.dll and cygstdc++-6.dll and put cygwig in glob variables, then my file worked in the same directory of main and exe.
However, thank you guys for your time!
fopen is a C solution for open a file if you want to open a file in c++ use fstream like flowing code.
fopen is deprecated in c++11.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
fstream myfile;
myfile.open("example.txt");
cerr << "Error: " << strerror(errno);
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
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;
}