C++ vector change in text.txt file and add text - c++

#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
#include <fstream>
#include <vector>
#include <iterator>
using std::cout;
using std::cin;
using std::endl;
using std::string;
std::string FilesOpen(std::string command)
{
const int size_buffer = 2;
char buffer[size_buffer];
memset(buffer, 0, size_buffer * sizeof(char));
std::string result = "";
// Open pipe to file
FILE* pipe = popen(command.c_str(), "r");
if (!pipe)
{
return "popen failed!";
}
// read till end of process:
while (!feof(pipe))
{
// use buffer to read and add to result
if (fgets(buffer, 2, pipe) != NULL)
{
result += buffer;
memset(buffer, 0, size_buffer * sizeof(char));
}
}
pclose(pipe);
return result;
}
int main(int* agrc, char* agrv[])
{
std::vector<std::string> pole;
std::string text;
// get files names and use to ifstream files
FilesOpen("ls /root/workspace/src/server > /root/workspace/filestext.txt");
// get files info size and names
FilesOpen("ls -l /root/workspace/src/server > /root/workspace/filelist.txt");
// get files name and add vector
std::ifstream files;
files.open("/root/workspace/filestext.txt", std::ios_base::in);
if (!files)
{
std::cout << "Error not open files" << std::endl;
}
while (files >> text)
{
pole.push_back(text);
}
files.close();
for (std::vector<std::string>::iterator it = pole.begin(); it != pole.end(); ++it)
{
std::cout << *it << std::endl;
}
// replace text in shell
std::string filereplace = "/root/workspace/testovaci.sh";
std::ofstream r_file(filereplace.c_str());
char patch[] = "patch=";
if (r_file.is_open())
{
for (int i = 0; patch[i] != '\0'; i++)
r_file.put(patch[i]);
r_file.put('D');
}
r_file.close()
}
I need to get the contents of the file name from the filetext.txt file and ignore the folders and list them in the testovaci.sh script, which looks like this:
neco1
neco2
neco3
patch =
neco4
neco5
I need to put in the testovaci.sh file has been added to patch = "file". "file". "file"
and the folders were ignored, leaving only binary files.
Please help me, as I tried everything but nothing works.

Related

How to get fstream to save to any windows desktop that opens the .exe in c++

I'm making a program for my brother that will display 50,000 proxie variations and will save them all to a .txt.
How can I make it so any windows machine that uses this code will get the .txt to save to the desktop.
Here's what I have:
fstream file;
file.open("proxies.txt", ios::out);
string line;
streambuf* stream_buffer_cout = cout.rdbuf();
streambuf* stream_buffer_cin = cin.rdbuf();
streambuf* stream_buffer_file = file.rdbuf();
cout.rdbuf(stream_buffer_file);
for (int i = 1; i < 50001; i++)
{
cout << n1 << i << n2 << "\n";
}
file.close();
Thanks for any help.
If I get what you are asking you just need to replace "proxies.txt" with an absolute path to a file in the desktop folder. You can get the desktop directory with the Win32 call SHGetFolderPath and put the path together using the standard (C++17) file system calls if you want, as below:
#include <iostream>
#include <filesystem>
#include <fstream>
#include <shlobj_core.h>
namespace fs = std::filesystem;
std::string desktop_directory() {
char path[MAX_PATH + 1];
if (SHGetFolderPathA(HWND_DESKTOP, CSIDL_DESKTOP, NULL,
SHGFP_TYPE_DEFAULT, path) == S_OK) {
return path;
} else {
return {}; // I'm not sure why this would fail...
}
}
int main() {
std::fstream file;
auto desktop_path = fs::path(desktop_directory()) / "proxies.txt";
file.open(desktop_path, std::ios::out);
// ...
file.close();
return 0;
}

no suitable conversion function from "const std::string" to "char *" exists?

im trying to make a simple program that list all txt file in the directory then append hello world in them but i face an issue while passing the vector into WriteFiles Function
this is the following code i've tried to fix it for a while any oil be grateful for any help
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;
void ListFiles(vector<string>& f) // list all files
{
FILE* pipe = NULL;
string pCmd = "dir /b /s *.txt ";
char buf[256];
if (NULL == (pipe = _popen(pCmd.c_str(), "rt")))
{
return;
}
while (!feof(pipe))
{
if (fgets(buf, 256, pipe) != NULL)
{
f.push_back(string(buf));
}
}
_pclose(pipe);
}
void WriteFiles (const char* file_name)
{
std::ofstream file;
file.open(file_name, std::ios_base::app); // append instead of overwrite
file << "Hello world";
file.close();
}
int main()
{
vector<string> files;
ListFiles(files);
vector<string>::const_iterator it = files.begin();
while (it != files.end())
{
WriteFiles(*it); // the issue is here
cout << "txt found :" << *it << endl;
it++;
}
}
WriteFiles(it->c_str()); will fix the problem. Iterators act a lot like pointers, so that's how you access a method indirectly.

Issue reading file with ifstream using absolute path

Hello stack overflow community. I came here as a last resort because i probably made a stupid mistake i cannot see myself.
The question im asking is for some reason when i try to read a file with an absolute path(or relative, you can see i tried that in my code) it cannot read the file for some unknown reason(atleast to me). This is a small thing for a big project im working on. Thank you guys!
main.cpp
#include <iostream>
#include <fstream>
#include <filesystem>
#include <unistd.h>
#include <string>
std::string openf() {
FILE* pipe = popen("zenity --file-selection", "r"); // open a pipe with zenity
if (!pipe) return "ERROR"; // if failed then return "ERROR"
char buffer[912]; // buffer to hold data
std::string result = ""; // result that you add too
while(!feof(pipe)) { // while not EOF read
if(fgets(buffer, 912, pipe) != NULL) // get path and store it into buffer
result += buffer; // add buffer to result
}
//I thought i needed to convert the absolute path to relative but i did not after all
// char cwd[10000];
// getcwd(cwd, 10000); // get cwd(current working directory)
// result = std::filesystem::relative(result, cwd); // convert the absolute path to relative with cwd
pclose(pipe); // cleanup
return result;
}
std::string readf(std::string filename){
std::string res;
std::ifstream file;
file.open(filename.c_str());
if(file.is_open()) {
while(file){
res += file.get();
}
}else {
std::cout << "failed to open file " + filename;
}
return res;
}
int main( void ){
std::string file = openf();
std::cout << file << std::endl;
std::string str = readf(file);
std::cout << str << std::endl;
return 0;
}
output
/home/meepmorp/Code/Odin/test/test.odin
failed to open file /home/meepmorp/Code/Odin/test/test.odin
It seems zenity, which you use as file chooser, outputs an extra newline after the file name, which you include in the name. In Linux, files can actually contain embedded newline characters in their name, and you actually try to open "test.odin\n" instead of "test.odin".

Read multiple files by passing them in argv[1]

This might be a basic question, but I am new to C++, so I would appreciate your understanding.
What I am trying to do is to read files from a folder and pass one of them at a time in argv[1], get some results from that file, write them in an output file specified in argv[2], then the same for the next file, and so on.
I guess it has something to do with pointers but I am not sure how to fix this.
Thank you for any input!
Here is what I have so far:
vector<string> getFilenames(string folder)
{
vector<string> names;
string search_path = folder + "/*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
names.push_back(fd.cFileName);
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
return names;
}
int main(int argc, char **argv) {
ofstream fileout(argv[2], ios::out | ios::app);
int a, b, c;
vector<string> filenames = getFilenames("folder path");
istringstream iss;
for (int i = 0; i < filenames.size(); i++) {
iss.str(filenames[i]);
iss >> argv[1];
if (readFile(a, b, c, argv[1]) == 0) {
/* do something */
}
}
fileout.close();
return 0;
}
I want to complete #Florian Klemme but I cannot comment.
There is a little example of how to iterate through command line parameters :
int main(int argc, char **argv)
{
for (auto i = int{0}; i < argc; ++i) {
// do something with argv[i];
}
}
I'm not exactly sure what your problem is but maybe this little example can help as a starting point. It shows how you can
Iterate though files in a directory (you need C++17 though)
Read some number from a file
Write to another file
Hopefully you can add the rest with no problem. :)
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
namespace fs = std::filesystem;
int main(int argc, char **argv) {
std::string input_dir = argv[1];
std::string output_file = argv[2];
std::ofstream out(output_file);
// Iterate over files in directory
for(auto& file : fs::directory_iterator(input_dir)) {
std::ifstream in(file.path());
// In this example, read a integer number from the current file
if (int i; in >> i) {
std::cout << "Read " << i << " from " << file << std::endl;
// ... and write it to the output file.
out << i << std::endl;
}
}
}

issue while creating binary files

I've written this code, which it get the repository and look for the files within. it aims to create binary files for each file found so as to write some data inside it later. However, the code is not running as expected. and the binary file are not created this the issue.
the directory has two images, and the output I get is as follows :
Creating bin files
C:\repo\1.bin
Error: failed to create file
Press <RETURN> to close this window...
I really do not know where I miss it. Any advice I'd be glad.
#include <vector>
#include <string>
#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <fstream>
using namespace std;
void getDir(string d, vector<string> & f)
{
FILE* pipe = NULL;
string pCmd = "dir /B /S " + string(d);
char buf[256];
if( NULL == (pipe = _popen(pCmd.c_str(),"rt")))
{
cout<<"Error"<<endl;
return;
}
while (!feof(pipe))
{
if(fgets(buf,256,pipe) != NULL)
{
f.push_back(string(buf));
}
}
_pclose(pipe);
}
void replaceExt(string& s, const string& newExt) {
string::size_type i = s.rfind('.', s.length());
if (i != string::npos) {
s.replace(i+1, newExt.length(), newExt);
}
}
using namespace std;
int main(int argc, char* argv[])
{
vector<string> files;
string path = "C:\\repo";
getDir(path, files);
vector<string>::const_iterator it = files.begin();
cout<<"Creating bin files "<<endl;
ofstream myOfstream;
while( it != files.end())
{
string fileName = (string) *it;
replaceExt(fileName, "bin");
cout << fileName << '\n';
std::stringstream ss;
ss << fileName << "" ;
myOfstream.open(ss.str(), fstream::binary);
if ( !myOfstream )
{
std::cerr << "Error: failed to create file " << '\n';
break;
}
myOfstream.close();
it++;
}
return 0;
}
First I have to say, if you directory you are looking for doesn't exists or is empty, the program gets locked, it would be nice to have that fixed if making a bigger program.
Then, for your case, I don't see whars the point of that stringstream, so I tried removing that, and changing it by a normal string, removing the last \n character you get from reading the filenames:
cout << fileName << '\n';
string ss = fileName.substr(0, fileName.size() - 1);
myOfstream.open(ss.c_str(), fstream::binary);
if (!myOfstream)
{
hope it helps
I found the issue bro, after debugging ;D
the problem is in the "newline", the string fileName has a "\n" at the end that's whats rise your error. Thus you have to erase it, I ve used this statement fileName.erase(std::remove(fileName.begin(), fileName.end(), '\n'), fileName.end());
and I included algorithm lib.
the working code is as follows :
#include <vector>
#include <string>
#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <fstream>
#include <algorithm>
using namespace std;
void getDir(string d, vector<string> & f)
{
FILE* pipe = NULL;
string pCmd = "dir /B /S " + string(d);
char buf[256];
if( NULL == (pipe = _popen(pCmd.c_str(),"rt")))
{
cout<<"Error"<<endl;
return;
}
while (!feof(pipe))
{
if(fgets(buf,256,pipe) != NULL)
{
f.push_back(string(buf));
}
}
_pclose(pipe);
}
void replaceExt(string& s, const string& newExt) {
string::size_type i = s.rfind('.', s.length());
if (i != string::npos) {
s.replace(i+1, newExt.length(), newExt);
}
}
using namespace std;
int main(int argc, char* argv[])
{
vector<string> files;
string path = "C:\\repo";
getDir(path, files);
vector<string>::const_iterator it = files.begin();
cout<<"Creating bin files "<<endl;
ofstream myOfstream;
while( it != files.end())
{
string fileName = (string) *it;
replaceExt(fileName, "bin");
cout << fileName << '\n';
fileName.erase(std::remove(fileName.begin(), fileName.end(), '\n'), fileName.end());
std::stringstream ss;
ss << fileName << "" ;
myOfstream.open(ss.str(), fstream::binary);
if ( !myOfstream )
{
std::cerr << "Error: failed to create file " << '\n';
break;
}
myOfstream.close();
it++;
}
return 0;
}