I want to read some input files in my c++ code and I want to define the path of input files as a string and then combine it with file names. How can I do this? (Input_path + filename.dat)
#include <filesystem> //C++ 17
#include <iostream>
namespace fs = std::filesystem;
using namespace std;
void main()
{
string dir("c:\\temp");
string fileName("my_file.txt");
fs::path fullPath = dir;
fullPath /= fileName;
cout << fullPath.c_str() << endl;
}
You would use something like:
string path ("yourFilePath");
string filename ("filename");
You could then open the file like this:
ifstream inputFileStream;
inputFileStream.open(path + fileName);
Depending on your requirements, you will have to decide whether to use formatted or unformatted input when reading. I would read this for more information regarding that.
Cocatenation referenced from: C++ string concatenation
Reading referenced from: C++ read and write with files
Try any of these codes:
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string filepath = "D:/location/";
filepath+= "filename.dat";
std::ifstream fp;
fp.open(filepath.c_str(),std::ios_base::binary);
....PROCESS THE FILE HERE
fp.close();
return 0;
}
or
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string filepath = "D:/location/";
std::ifstream fp;
fp.open((filepath+"filename.dat").c_str(),std::ios_base::binary);
...............
fp.close();
return 0;
}
or use std::string::append
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string filepath = "D:/location/";
std::ifstream fp;
fp.open((filepath.append("filename.dat")).c_str(),std::ios_base::binary);
fp.close();
return 0;
}
Related
Im new to coding c++ and i am trying to call a function from another file to check if the string containing the text file is made up of alphabetic characters, but for some reason it is not working.
I am getting errors in my ap.cpp file saying
Invalid arguments '
Candidates are:
bool is_alpha(?)
'
and
‘is_alpha’ cannot be used as a function
and also errors in my header file saying
Type 'string' could not be resolved
MY CODE:
AP.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "functions.h"
using namespace std;
int main () {
string line;
string textFile;
ifstream myfile ("encrypted_text");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
textFile += line;
}
myfile.close();
}
else cout << "Unable to open file";
bool check = is_alpha(textFile);
if (check){
cout << "true";
} else cout << "false";
return 0;
}
checkFunctions.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include "functions.h"
using namespace std;
bool is_alpha (string str) {
for(int i=0; i < str.size(); i++)
{
if( !isalpha(str[i]) || !isspace(str[i]))
{
return true;
}
}
return false;
}
functions.h
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <string>
bool is_alpha(string str);
#endif /* FUNCTIONS_H_ */
It'll be the best if you not use using namespace std; until you have a proper understanding about the language and its implications. If you were wondering what using namespace does is, it basically sets the content in the namespace and puts it to the global namespace (in which you don't need to specify where it comes from, in this its std and the way to call it is std::).
The error is because the compiler doesn't know where the string in bool is_alpha(string str); comes from. So to solve this, take my first advice to consideration and you can specify where it comes from like this: bool is_alpha(std::string str);.
Plus you don't need to add the libraries included in a header file again in the source file. This means that you can remove the #include <string> from AP.cpp and checkFunctions.cpp.
More about header files: https://stackoverflow.com/a/9224641/11228029
I'm pretty new to C++ and I wanted to start working with files so I ended up doing this :
#include <iostream>
#include <string>
#include <cstdlib>
#include <windows.h>
#include <stdexcept>
#include <limits>
#include <Lmcons.h>
#include <fstream>
using namespace std;
void out(string x){x+="\n";cout<<x;}
void outn(){out("");}
void delay(int x){Sleep(x);}
void delayS(int x){Sleep(x*1000);}
void cs(){std::system("cls");}
void UserName(string *x){char username[UNLEN + 1];DWORD size = UNLEN + 1;GetUserName(username, &size);string transition(username);*x=transition;}
//use this synthax in main : char user[20];string username(user);UserName(&username);
using namespace std;
int main()
{
char user[20];string username(user);UserName(&username);
out(username);
delayS(2);
cs();
string beginning="C:\\Users\\" ;
string path;
string ending="\\Desktop\\";
string filename;
out("file name = ");
cin>>filename;
path+=beginning;
out(path);
delayS(2);
path+=username;
out(path);
delayS(2);
path+=ending;
out(path);
delayS(2);
path+=filename;
out(path);
delayS(2);
ofstream file;
try{
file.open(path ,ios::in);
if(!file.is_open()){throw 404;}
else{
file.open(path,ios::out|ios::app);
file<<"\n";
file<<"lol";}
}catch(int x){cout<<"Error "<<x<<" : file not found";}
return 0;
}
Which result in this error (line 59) :
" no matching function for call to 'std::basic_ofstream::open(std::string&, std::_Ios_Openmode)' "
image of error : https://imgur.com/YVBHDzq
May I have some help ?
EDIT: I'm using Codeblocks 16.01
In pre-C++11, you need to pass a const char* to ofstream::open() as the first parameter:
file.open( path.c_str(), ios::in );
#include <iostream>
#include <windows.h>
#include <Lmcons.h>
#include <fstream>
using namespace std;
main(){
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
string cmd("C:\\Users\\");
cmd+=username;
cmd+=("\\AppData\\Roaming\\MiniApps");
}
Now I have complete path url in "cmd", and i want to use this variable as a path in c++ file handling . like
ofstream file;
file.open(cmd,ios::out|ios::app);
Open a file stream using ofstream, write the content and close.
#include<iostream>
#include <windows.h>
#include <Lmcons.h>
#include <fstream>
#include <string>
int main(){
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
std::string cmd("C:\\Users\\");
cmd+=username;
cmd+=("\\AppData\\Roaming\\MiniApps.txt");
std::ofstream file;
file.open (cmd.c_str(), std::ofstream::out | std::ofstream::app);
file << " Hello World";
file.close();
return 0;
}
With C++11 you can do
ofstream file(cmd,ios::app);
Without you have to do
ofstream file(cmd.c_str(),ios::app);
In my current project, I have to go to a certain user inputted directory, open that directory and read all the zip files in that directory which begin with W. I am trying to use the XZIP library for opening the ZIP files, but I am certainly doing something very wrong. I am confused whether to use UnzipItem or Openzip to open the zip file and parse through its contents. (The zip files each contain some .jpg files and I have to copy those files into another location, but that's the second part of the project)
I would really appreciate some help, Thanks :)
Here is my code-
#include "StdAfx.h"
#include "src\XZip.h"
#include "src\XUnzip.h"
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include "src\dirent.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <windows.h>
int main()
{
std::ifstream fin;
std::string dir, filepath;
int num;
DIR *dp;
struct dirent *dirp;
struct stat filestat;
std::string filename;
std::string userInput;
std::cout << " Input dir to get files from : ";
getline( std::cin, dir ); // gets everything the user
dp = opendir( dir.c_str() );
if (dp == NULL)
{
std::cout << "Error opening " << dir << std::endl;
}
char test[2];
while ((dirp = readdir( dp )) != NULL)
{ // printf(" inside the directory ");
filepath = dir+"/" + dirp->d_name;
filename =dirp->d_name;
test[0]=filename[0];
test[1]='\0';
if ( test[0]=='W')
{ HZIP* z;
DWORD File_name = std::strtoul(filename.c_str(), NULL, 16);
OpenZip(z,0,File_name);
}
}
return 0;
}
From the docs I'd say that you first need to call OpenZip to get a handle back and with that handle call UzipItem with an item id you got from FindZipItem.
All i have is the documentation:
flags - indicates usage, see below; for files, this will be ZIP_FILENAME
So i guess something like: auto handle = OpenZip("file.zip", 0, ZIP_FILENAME);
Basically I need to open and read a list of files I get from another command.
For each line of output of popen
open a file usen ifstream.open
it compiles and if I put the file name directly it works fine, but it doesn't do anything when using popen output. I've seen questions like this but none of this particular way of giving filenames.
here's the code:
#include <iostream>
#include <sqlite3.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
ifstream singlefile;
FILE *filelist;
char filename[512];
string progline;
if(!(filelist = popen("find `pwd` -name \"*.js\"", "r"))){
return 1;
}
while( fgets(filename, sizeof(filename), filelist)!=NULL)
{
cout << filename;
singlefile.open(filename, ifstream::in);
while ( singlefile.good() )
{
getline (singlefile,progline);
cout << progline << endl;
}
singlefile.close();
}
pclose(filelist);
return 0;
}
next step would be not open each file inside the loop but to store the file list and then open each file.
Thanks
fgets keeps the trailing newline, resulting in a filename of a non-existing file. Also the stream state is only updated after reading. If I replace the while body with the following code, it works for me:
cout << filename;
size_t len = strlen(filename);
// chop off trailing newline
if (len > 1 && filename[len - 1] == '\n') filename[len - 1] = 0;
singlefile.open(filename, ifstream::in);
while ( getline(singlefile, progline) )
{
cout << progline << endl;
}
singlefile.close();
If you actually want to iterate through a list of files, I'd use Boost.Filesystem, which has a nice C++ interface, works for all filenames (even for those with newlines), and is platform-independent.
If this actually is only an example and your actual command is not find, there is still some room for simplification. Here is a suggestion that uses Boost.Iostreams to get rid of most of the C function calls (it would be great to have a device source reading from a process's standard output, but Boost.Iostreams lacks that):
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
using namespace std;
namespace io = boost::iostreams;
class Popen: private boost::noncopyable {
public:
explicit Popen(const char* command):
m_stream(popen(command, "r")) {
if (!m_stream) throw runtime_error("popen failed");
}
~Popen() {
pclose(m_stream);
}
FILE* stream() const {
return m_stream;
}
private:
FILE* m_stream;
};
int main() {
Popen pipe_wrapper("find `pwd` -name \"*.cpp\"");
io::file_descriptor_source pipe_device(fileno(pipe_wrapper.stream()), io::never_close_handle);
io::stream<io::file_descriptor_source> pipe_stream(pipe_device, 0x1000, 0x1000);
string filename;
while (getline(pipe_stream, filename)) {
cout << filename << endl;
ifstream file_stream(filename.c_str(), ifstream::in);
string progline;
while (getline(file_stream, progline)) {
cout << progline << endl;
}
}
}