Copy vector to clipboard - c++

Hi my goal is to take each line from input.txt load them into a vector and then copy each vector to the clipboard every 1 second.
So far I am able to load the file into a vector using getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
I am also able to copy a string to the clipboard if I replace:
cout << "Lines Copying " << endl;
with
cout << "Please enter sentence: "; cin >> AAA;
Using the users input...
However, when I try to load the vector called line I get 0 char(s) copied to clipboard?
What am I doing wrong? Any pointers or suggestions will be greatly appreciated..
Using:
Windows 10 64x
Microsoft Visual Studio Community 2015
Version 14.0.23107.0 D14REL
Microsoft .NET Framework
Version 4.7.02046
Visual C++ 2015 00322-20000-00000-AA355
Microsoft Visual C++ 2015
input.txt:
The
Brown
Fox
Jumps
Script:
// copyfilelines.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <vector>
#include <direct.h>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <winuser.h>
#include <cmath>
#include <iomanip>
#include <complex>
void toClipboard(HWND hwnd, const std::string &s);
/*
* It will iterate through all the lines in file and
* put them in given vector then copy vector to clipboard.
*/
//1. Open file and put each line into a vector.
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid.
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector.
if (str.size() > 0)
vecOfStrs.push_back(str);
}
// Close The File.
in.close();
return true;
}
//2. Declare clipboard functions at file scope.
void toClipboard(HWND hwnd, const std::string &s) {
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
if (!hg) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
int main()
{
std::vector<std::string> vecOfStr;
// Get the contents of file in a vector.
bool result = getFileContent("input.txt", vecOfStr);
if (result)
{
// Print the vector contents.
for (std::string & line : vecOfStr)
std::cout << line << std::endl;
// Copy vector to clipboard.
using namespace std;
string line;
cout << endl;
cout << endl;
cout << "Lines Copying " << endl;
cout << endl;
cout << endl;
cout << "Lines Copied To The Clipboard: ";
cout << endl;
cout << line << endl;
// 1. Strlen takes a const char*, so have to call the strings c_str() method
// (but it would be better to use len = line.length() instead)
size_t len = strlen(line.c_str());
cout << len << " char(s)" << endl;
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, line);
//User input processing.
//cin.clear();
//cin.ignore(255, '\n');
//cin.get();
}
return 0;
}
EDIT:
Updated script
I added a std::ostream_iterator to allow streaming of a vector:
std::stringstream ss;
// Populate
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
// Display
std::cout << ss.str() << std::endl;
// Copy vector to clipboard.
size_t len = strlen(ss.str().c_str());
Full Updated Script:
Streams content of input.txt and copies all streamed content to clipboard.
// copyfilelines.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <fstream>
#include <string>
#include <vector>
#include <direct.h>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <winuser.h>
#include <cmath>
#include <iomanip>
#include <complex>
#include <iostream>
#include <sstream>
#include <iterator>
void toClipboard(HWND hwnd, const std::string &s);
/*
* It will iterate through all the lines in file and
* put them in given vector then copy vector to clipboard.
*/
//1. Open file and put each line into a vector.
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid.
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector.
if (str.size() > 0)
vecOfStrs.push_back(str);
}
// Close The File.
in.close();
return true;
}
//2. Declare clipboard functions at file scope.
void toClipboard(HWND hwnd, const std::string &s) {
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
if (!hg) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
int main()
{
std::vector<std::string> vecOfStr;
// Get the contents of file in a vector.
bool result = getFileContent("input.txt", vecOfStr);
if (result)
{
std::stringstream ss;
// Populate
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
// Display
std::cout << ss.str() << std::endl;
// Copy vector to clipboard.
size_t len = strlen(ss.str().c_str());
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, ss.str());
Sleep(100000);
}
return 0;
}

Ignoring all the irrelevant printing to cout, your code is:
if (result)
{
// Copy vector to clipboard.
using namespace std;
string line;
size_t len = strlen(line.c_str());
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, line);
}
You have a default constructed string called line, and you copy that to the clipboard. Not surprisingly, it contains no characters. I think you need to create a stringstream and print the vector to that, and then copy that to the clipboard.

Related

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

#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.

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 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;
}

Process file lines stream iterator

Hi I have this script below which streams all the data line by line from input.txt
once that is done the streamed data is then copied to the clipboard.
I want to stream one line process and copy that line, then stream&copy the next line ...and so on.
E.G:
open input.txt copy first streamed line to clipboard, run mouse click macro, run paste macro
then
copy second streamed line to clipboard, run mouse click macro, run paste macro...
loop this over input.txt
I have already used /n as a deliminator in the iterator stream to separate each line
// copyfilelines.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <fstream>
#include <string>
#include <vector>
#include <direct.h>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <winuser.h>
#include <cmath>
#include <iomanip>
#include <complex>
#include <iostream>
#include <sstream>
#include <iterator>
void toClipboard(HWND hwnd, const std::string &s);
/*
* It will iterate through all the lines in file and
* put them in given vector then copy vector to clipboard.
*/
//1. Open file and put each line into a vector.
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid.
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector.
if (str.size() > 0)
vecOfStrs.push_back(str);
}
// Close The File.
in.close();
return true;
}
//2. Declare clipboard functions at file scope.
void toClipboard(HWND hwnd, const std::string &s) {
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
if (!hg) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
int main()
{
std::vector<std::string> vecOfStr;
// Get the contents of file in a vector.
bool result = getFileContent("input.txt", vecOfStr);
if (result)
{
std::stringstream ss;
// Populate
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
// Display
std::cout << ss.str() << std::endl;
// Copy vector to clipboard.
size_t len = strlen(ss.str().c_str());
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, ss.str());
Sleep(100000);
}
return 0;
}
This line makes your program work on all the lines of the file (now stored as elements in a vector) in one go.
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
To make it work line by line instead, just iterate the elements of the storage vector individually with a for loop.
for (auto str : vecOfStr)
{
toClipboard(hwnd, str);
// run mouse click macro, run paste macro...
}

Store lines from a text file in a list of strings

I've been trying to store the lines of a text file in a list in C++. Better, I've been trying to store each word of each line of the text file in a string that is part of a list of strings, but it seems that I'm doing it in the wrong way.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
using namespace std;
int main()
{
FILE *f= fopen("teste.txt", "r");
size_t len= 100; // valor arbitrário
char *line= (char*)malloc(len);
std::list<string> mylist;
if (!f)
{
perror("teste.txt");
exit(1);
}
while (getline(&line, &len, f) > 0)
{ //THE REAL PROBLEM
for (std::list<string>::iterator it = mylist.begin(); it != mylist.end(); it++){
*it=line;
cout << *it << '\n';
}
}
if (line)
free(line);
fclose(f);
return 0;
}
The exact problem is that this doesn't give any result. It compiles but nothing results from this.
Thanks in advance.
Change your while loop as follows:
while (getline(&line, &len, f) > 0)
{
mylist.push_back(line);
cout << mylist.back() << '\n';
}
You cannot access any non initialized items from a std::list<>.
Also NOTE you should make line a std::string, and omit the malloc() / free() calls from your code.
2nd NOTE: Use std::ifstream instead of FILE* for an input file stream.
Here's the fully fixed (no more errors/exceptions on ideone) code sample:
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <exception>
#include <errno.h>
#include <stdlib.h>
int main()
{
try
{
std::ifstream f("teste.txt");
if(!f)
{
std::cerr << "ERROR: Cannot open 'teste.txt'!" << std::endl;
exit(1);
}
std::string line;
std::list<std::string> mylist;
while (std::getline(f,line))
{
mylist.push_back(line);
std::cout << mylist.back() << std::endl;
}
}
catch(const std::exception& ex)
{
std::cerr << "Exception: '" << ex.what() << "'!" << std::endl;
exit(1);
}
exit(0);
}
You can not assign a char* value to std::string by using '=' operator.
Change
*it=line to
it->assign(line,line+strlen(line);