I am simply want to read text from a file and don't know why code is not working. I have already put correct text file name on folder from where program is running. I must be doing something small. Please highlight issue in code below:
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include<cstdio>
using namespace std;
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
std::string get_working_path() {
char cwd[1024];
if (GetCurrentDir(cwd, sizeof(cwd)) != NULL)
return std::string(cwd);
else
return std::string("");
}
int main() {
string line;
//ofstream myfile;
//myfile.open("cmesymbols.txt", ios::out | ios::app | ios::binary);
ifstream myfile("cmd.txt");
if (myfile.is_open()) {
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else
std::cout << "File not found in cwd: " << get_working_path();
myfile.close();
return 0;
}
Output: File not found in cwd:
This code is working fine. I found that folder settings in machine is to hide known extensions of files. I deliberately put name as "cmd.txt" however actual name came up as "cmd.txt.txt" and because of this code is not finding this file..
I corrected file name as "cmd.txt" and the code is working now.
ifstream myfile("cmd.txt"); doesn't create the file for you.
So make sure the file "cmd.txt" exists in your project directory together with your main.cpp (or main source file).
Related
I am trying to open a csv file in C++ using ifstream with a directory in the file path name. The file does reside in the specified directory location, but I observe an for the variable inFile when executing the code. My research up to this point says the code is correct, but something obviously is wrong. Any suggestions?
Thanks,
KG
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open("csvFile", ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
I found the answer to my csv file opening problem, a colleague assisted.
#David - You suggested removing the double quotes in the "inFile.open" line of code. In addition to removing the double quotes, I also needed to add c_str(), which "returns a pointer to a null-terminated character array with data equivalent to those stored in the string," .data() also performs the same function (cppreference.com).
#user4581301 - I am also aware that ios::in is implied with a ifstream, only included it here as a reference; thanks.
The modified code is listed below:
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open(csvFile.c_str(), ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
Really appreciate all the help.
Enjoy,
KG
Is this what you're trying to do?
#include <iostream> // std::{ cout, endl }
#include <string> // std::{ string, getline }
#include <fstream> // std::ifstream
auto main() -> int {
// Just to demonstrate.
// You want to use your real path instead of example.cpp
auto file = std::ifstream("example.cpp");
auto line = std::string();
while ( std::getline(file, line) )
std::cout << line << '\n';
std::endl(std::cout);
}
Live example
I'm failing to open a .txt file using std::ifstream file and file.open(). I want to use an indirect PATH (starting in the folder the .exe file is in - \program_folder), but using a complete PATH (C:\Users\Rafael\Desktop\C++\program_folder\inputs\test.txt) also didn't work.
#include <iostram>
#include <vector>
#include <string>
#include <fstream>
int main(){
char c;
std::vector<std::string> inputs;
inputs.push_back("C:\\inputs\\test.txt");
int a; int b;
std::ifstream file;
file.open(inputs[0]);
if (file.is_open()){
c = file.get();
file.close();
}
else {std::cout << "\nfail to open file";}
}
As output, I'm getting the fail massage.
"C::\\inputs\\test.txt" was not a relative path i had to use "inputs\\test.txt"
thanks to john in the comments.
I have this code in C++:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string str;
ifstream file("file.txt");
file >> str;
cout << str;
return 0;
}
I have file.txt in the same directory as main.cpp. I get no output from this, I've tried specifying full filepath to the file and still no result and tried it on few different machines too.
Does anybody know what I'm doing wrong?
What you're interested in is the current working directory for your program, i.e. where your text file is supposed to be if you don't qualify it with a full or relative path.
You can get it at runtime with getcwd (linux) or _getcwd (windows).
Edit: I agree with Andy, you should anyway check for errors when opening files. You could have caught this earlier (i.e. file not found), e.g.
(pseudocode ahead for illustrative purposes)
#include <unistd.h>
// Warning: linux-only, use #ifdefs and _getcwd for windows OS
std::string get_working_path() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL)
return std::string(cwd);
else
return std::string("");
}
int main() {
std::string str;
std::ifstream file("file.txt");
if (file >> str)
std::cout << str;
else {
std::cout << "File not found in cwd: " << get_working_path();
// abort
}
// ...
}
Hey all, I have a problem, I don't know how to create a file in C++ in a specific place in the PC. For example a file (.txt) in C:\file.txt. Can anybody help me? Thank you :)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream ofs("c:\\file.txt");
if (ofs) {
ofs << "hello, world!\n";
}
return 0;
}
It's probably fooling you because it's easier than you think. You just open a file for create and give it that path name. Voila.
See, eg,
// fstream::open
#include <fstream>
using namespace std;
int main () {
fstream filestr;
// You need a doubled backslash in a C string
filestr.open ("C:\\file.txt", fstream::out);
// >> i/o operations here <<
filestr.close();
return 0;
}
#include <stdio.h>
....
FILE *file;
file = fopen("c:/file.txt", "w");
I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.
Can anyone help me?
One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
ofstream reference
For completeness, here's some example code:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.
Do this with a file stream. When a std::ofstream is closed, the file is created. I prefer the following code, because the OP only asks to create a file, not to write in it:
#include <fstream>
int main()
{
std::ofstream { "Hello.txt" };
// Hello.txt has been created here
}
The stream is destroyed right after its creation, so the stream is closed inside the destructor and thus the file is created.
#include <iostream>
#include <fstream>
int main() {
std::ofstream o("Hello.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string filename = "/tmp/filename.txt";
int main() {
std::ofstream o(filename.c_str());
o << "Hello, World\n" << std::endl;
return 0;
}
This is what I had to do in order to use a variable for the filename instead of a regular string.
Here is my solution:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.
If you want to create a file with some content and don't need to deal with the ofstream after that you can simply write:
#include <fstream>
int main() {
std::ofstream("file.txt") << "file content";
}
no need to manually close the file, deal with variables, etc. The file is created, written, and closed in the same line.
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
use c methods FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending
r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();